Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why tack a protocol of NSObject to a protocol implementation

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.

like image 809
Coocoo4Cocoa Avatar asked Mar 25 '09 00:03

Coocoo4Cocoa


2 Answers

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.

like image 132
Barry Wark Avatar answered Sep 28 '22 00:09

Barry Wark


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.

like image 22
Lounges Avatar answered Sep 28 '22 01:09

Lounges