Explanation
I've seen this happen when there are circular references between .h files. #import
prevents the file from being included twice, but it sometimes means that classes aren't declared exactly where you expect. Here's what happens:
ClassA.m:
#import "ClassA.h"
...
ClassA.h
#import "ClassB.h"
@interface ClassA : ClassB
@end
ClassB.h
#import "ClassA.h"
@interface ClassB
@property (nonatomic) ClassA *classA;
@end
- ClassA.m imports ClassA.h.
- ClassA.h imports ClassB.h before declaring ClassA.
- ClassB.h imports ClassA.h, but it's already been imported, so this is ignored.
- ClassB tries to use ClassA, but it's not declared yet.
Solution
What I usually do is to #import
just the base class in the .h file, forward declare any types needed by the class interface, and #import
the rest of the .h files in the .m file:
ClassA.m:
#import "ClassA.h"
#import "ClassB.h"
...
ClassA.h
#import "ClassB.h"
@interface ClassA : ClassB
@end
ClassB.h
@class ClassA;
@interface ClassB
@property (nonatomic) ClassA *classA;
@end