Question

Minimum Example "Test.h":

#import <Foundation/Foundation.h>

@protocol CallBack <NSObject>

-(void)method;

@end

@interface Test : NSObject

-(void)callback:(CallBack*)theCallback;

@end

And the corresponding "Test.m":

#import "Test.h"

@implementation Test

-(void)callback:(CallBack*)theCallback
{
    [theCallback method];
}
@end

This will give me a "Expected a Type" error for the CallBack parameter both in the .m and the .h file. As the CallBack protocol is defined before everything else, i can't see why the compiler can't find it. If i add a Forward-Definition @class CallBack; at the beginning of the header file it will give me a "Receiver type 'CallBack' for instance message is a forward declaration" error for the line [theCallback method].

why can't the compiler find the protocol?

Was it helpful?

Solution

The correct syntax to refer to an object that conforms to the CallBack protocol is id<CallBack>.

Thus, you might want:

@protocol CallBack <NSObject>

-(void)method;

@end

@interface Test : NSObject

-(void)callback:(id <CallBack>)theCallback;

@end

and

@implementation Test

-(void)callback:(id <CallBack>)theCallback
{
    [theCallback method];
}
@end

For more information, see Working with Protocols in the Programming with Objective-C guide.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top