標籤:
問題來源:
常見面試問題之:
NSObject和NSObject protocol有什麼區別,為什麼要有NSObject protocol, 有沒有不繼承自NSObject的類?
雖然在iOS開發過程中所用到的幾乎所有的類都派生自NSObject, 但Cocoa並不是只有一個NSObject這一個root class. 另一個典型的root class就是NSProxy. 這也就是為什麼同時需要定義NSObject類和NSObject協議. 那些不是從NSObject派生的類,也可以實現NSObject protocol的. 也就是說,NSObject class和NSObject protocol本身是相互獨立的,按照正常的對類的理解和對協議的理解去理解這個事情就可以了。當然,NSObject protocol協議存在的必要性就是因為不是所有的類都派生自NSObject.
在NSProtocol的定義中有如下的方法:
- (BOOL)isProxy;
這個方法就可以用來判斷這個類是否是從其他的根類派生.
文檔描述如下:
- (BOOL)isProxy |
Description |
Returns a Boolean value that indicates whether the receiver does not descend from NSObject. (required) |
|
This method is necessary because sending isKindOfClass: or isMemberOfClass: to an NSProxy object will test the object the proxy stands in for, not the proxy itself. Use this method to test if the receiver is a proxy (or a member of some other root class). |
Returns |
NO if the receiver really descends from NSObject, otherwise YES. |
至於NSProxy本身,一般iOS開發中會比較少用。NSProxy可以用來實現代理模式和類比多繼承;具體的可以參見如下的博文:
使用NSProxy實現代理模式 : http://blog.csdn.net/onlyou930/article/details/7548476
使用NSProxy實現訊息轉寄機制,類比多重繼承: http://blog.csdn.net/onlyou930/article/details/7548634
另有如下文章詳細的描述NSObject class與NSObject protocol的,我比較懶,就直接貼連結了:
原文:NSObject: the Class and the Protocol https://mikeash.com/pyblog/friday-qa-2013-10-25-nsobject-the-class-and-the-protocol.html
譯文:http://my.oschina.net/yongbin45/blog/202535
iOS root class