Objective C: Expected '(' before 'Project'
A mistake I’ve made more than a few times while declaring headers in Objective C is forgetting to explicitly import the classes used in the interface definition.
I’ve been refactoring some of the code I wrote earlier in the week and wanted to create a 'LabelFactory'. I had the following code:
LabelFactory.h
#import <UIKit/UIKit.h>
@interface LabelFactory : NSObject {
}
+ (UILabel*)createLabelFrom:(Project *)project withXCoordinate:(NSInteger)x withYCoordinate:(NSInteger)y;
@end
Which gives this error on compilation:
/Users/mneedham/SandBox/iPad/CIMon/LabelFactory.h:9:0 /Users/mneedham/SandBox/iPad/CIMon/LabelFactory.h:9: error: expected ')' before 'Project'
I’ve been wondering what that error message actually means for a while and more by accident than design I re-read the section of Apple’s documentation on 'referring to other classes'
An interface file declares a class and, by importing its superclass, implicitly contains declarations for all inherited classes, from NSObject on down through its superclass. If the interface mentions classes not in this hierarchy, it must import them explicitly or declare them with the @class directive:
Declaring 'Project' with the '@class' directive just above '@interface' helps fix that problem:
...
@class Project;
@interface LabelFactory : NSObject {
}
...
The original error message I was getting is still slightly mystifying to me…
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.