fabian789
fabian789

Reputation: 8412

Using delegate declaration in multiple classes

Let's say I have a class ClassA which declares a protocol 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?

Upvotes: 1

Views: 296

Answers (2)

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...

Upvotes: 2

theChrisKent
theChrisKent

Reputation: 15099

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

Upvotes: 3

Related Questions