Declare protocol before defining it?
I was looking at ways to declare a protocol without defining, if such a thing makes sense. By declare I mean somehow telling the compiler the name of a protocol only, without defining the methods that should be adopted. This is similar to @class for classes,
@class MyClass;
The reason I wanted to do so was because I had a header file that looked like this,
@interface MyClass {
id mDelegate;
}
@property (nonatomic, retain) id mDelegate;
@end
@protocol MyDelegateProtocol
- (void) doStuff;
@end
This works fine. However, I don’t like the following because I’m not being specific on the type for mDelegate,
id mDelegate;
Being a Java programmer, I instinctively tried MyDelegateProtocol* mDelegate, which doesn’t work. The solution is to move the protocol definition before the interface declaration and use id<MyDelegateProtocol>,
@protocol MyDelegateProtocol
- (void) doStuff;
@end
@interface MyClass {
id<MyDelegateProtocol> mDelegate;
}
@property (nonatomic, retain) id<MyDelegateProtocol> mDelegate;
@end
I then got the error
-release not found in protocol(s)
Inheriting from NSObject did the trick,
@protocol MyDelegateProtocol <NSObject>
Posted in: Objective C, Uncategorized
Leave a comment

