In order to keep my build times down and also to keep my code as succinct as possible, I've been using forward-declarations in my header files and placing my #import
statements in my implementation files. This has been working great so far, however I've come across a problem. Suppose I have a class MyClass
that returns an object of class Widget
, such as:
@interface MyClass : NSObject
-(Widget*)widgetWithName:(NSString*)name;
@end
Assume Widget
has a method -(void)arbitraryMethod;
Now, suppose I am implementing a class that imports MyClass.h
, instantiates a MyClass
object, performs widgetWithName:
, and then tries to send the arbitraryMethod
message to the returned Widget
, I get the error receiver type "Widget" for instance message is a forward declaration
. So, I have to go ahead and import the Widget.h
header file to fix the error.
Of course, this is never a problem when I'm returning Foundation
classes because #import <Foundation/Foundation.h>
is in Prefix.pch
.
What is the best practice? My gut feeling is that if I'm returning a class or using that class as an argument in a public method, the header file should be included in my header file. Otherwise, if I had a class that used ten different non-foundation classes in public facing methods, my users would have to hunt down and import a new header file into their project every time they wanted to use that method.
Is this correct or is there a better pattern to use?