Why use the NSObject protocol to implement the protocol

I saw code similar to the following:

@protocol MyProtocol <NSObject> // write some methods. @end 

Is there any specific reason MyProtocol complies with NSObject? Isn't that too redundant if you do something like:

 id <MyProtocol> foo; // foo here conforms to NSObject AND MyProtocol? 

Just wondering what logic is.

+29
objective-c iphone cocoa
Mar 25 '09 at 0:45
source share
5 answers

I'm sure the reason you do this is to add NSObject members to your protocol (e.g. save and release). Technically, you can still send these messages, but you will get a compiler warning without it.

+27
Mar 25 '09 at 1:20
source share

When you declare a type variable

  id<MyProtocol> var; 

the Objective-C compiler only knows about the methods in MyProtocol and thus will warn you if you try to call any of the NSObject methods, such as -retain/-release , in this instance. Thus, Cocoa defines the NSObject protocol, which reflects the methods of the NSObject class and instance. MyProtocol announcing that MyProtocol implements the NSObject protocol, you give the compiler a hint that all 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 also the root class. Therefore, an instance of type id does not necessarily inherit NSObject methods.

+30
Mar 25 '09 at 17:45
source share

It is also very convenient when you have protocols with @optional methods (for example, the "modern" Objective-C delegates 2.0 often use this method). If you did not NSObject protocol, you will receive warnings when you try to call respondsToSelector: on an object.

+20
Mar 25 '09 at 1:45
source share

I never did this in my code, but I could see its advantage. If you pass the parameter as id <SomeProtocol> , you will need to resend it if you want to call any of the NSObject methods on this object.

+2
Mar 25 '09 at 0:53
source share

If you use any of the NSObject protocol methods, such as saving, issuing, class, class name, the compiler will give you warnings if your protocol also does not contain the NSObject protocol.

+1
Mar 26 '09 at 18:57
source share



All Articles