Let's say I have a class ClassA
which declares a pro开发者_JS百科tocol in ClassA.h
:
@protocol SomeProtocol
- (void)myMethod;
@end
Now, let's say I also have a class ClassB
. I would really like to use the SomeProtocol
in ClassB
like so:
#import ClassA.h
@interface ClassB : NSObject
{
id <SomeProtocol> someObject;
}
but the complier keeps telling me that it "Cannot find protocol declaration for "SomeProtocol".
Any ideas of what I am missing?
Change your ClassB to look like this:
@protocol SomeProtocol;
@interface ClassB : NSObject
{
id <SomeProtocol> someObject;
}
Just to clarify, using the @protocol directive like this just informs the compiler that SomeProtocol is a protocol that will be defined later. This just make a forward reference to the protocol without needing to import the interface where it is defined.
More information can be found here (Very bottom): http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProtocols.html
You can also put the protocol in SomeProtocol.h (its own header file) and import it from both class A and class B.
If you don't import the protocol you'll not get nice compile time warnings telling you when you are making a mistake calling it...
精彩评论