I have been seeing some code around that resembles the following:
@protocol MyProtocol <NSObject> // write some methods. @end
Is there any particular reason why MyProtocol conforms to the NSObject protocol? Isn't that rather redundant in that if you do something such as:
id <MyProtocol> foo; // foo here conforms to NSObject AND MyProtocol?
Just curious what the logic is.
When you declare a variable like
id<MyProtocol> var;
the Objective-C compiler knows only about the methods in MyProtocol
and will thus produce a warning if you try to call any of the NSObject
methods, such as -retain/-release
, on that instance. Thus, Cocoa defines an NSObject
protocol that mirrors the NSObject
class and instance methods. By declaring that MyProtocol
implements the NSObject
protocol, you give the compiler a hint that all of the NSObject
methods will be implemented by an instance that implements MyProtocol
.
Why is all this necessary? Objective-C allows objects to descend from any root class. In Cocoa, NSObject is the most common, but not the only root class. NSProxy
is also a root class, for example. Therefore an instance of type id
does not necessarily inherit NSObject
's methods.
I'm pretty sure the reason you would do this is to add the NSObject members (say like retain and release) to your protocol. Technically you can still send those messages anyways but you will get a compiler warning without it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With