iOS root class

來源:互聯網
上載者:User

標籤:

問題來源:

常見面試問題之:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.