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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…