Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
346 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...