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

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

iphone - 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.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...