1. 程式人生 > >Objective-C中C語言使用初步學習

Objective-C中C語言使用初步學習

最近在進行iOS的深入學習,看過一些部落格後意識到自己的程式碼寫的過於臃腫。我從開始學習到現在的業務熟練都是使用的最基本的MVC模式,於是MVC中的C--controller程式碼十分臃腫,讓接手程式碼的人無從下手。在網上查閱多篇部落格後,才瞭解到有多種設計模式,雖然各有缺點,但是能讓我借鑑到許多方法;然後還找到很多模組,比如YYKit等,可以優化、簡化複雜的程式碼模組和邏輯。

現在我就在學習YYKit,發現其中使用了大量的C語言。C語言眾所周知可以優化效能,所以我首先YYKit中學習C語言的使用。

isa與meta-class

大部分內容還是從其它部落格中學習到的,把其中的知識點圈出來記錄下來。

每一個OC物件都有一個隱藏的資料結構,這個資料結構是OC物件的第一個成員變數——isa指標。

isa是什麼呢?官方介紹是這樣的:


Every object is connected to the run-time system through itsisa instance variable, inherited from the NSObject class.isa identifies the object's class; it points to a structurethat's compiled from the class definition. Through isa, anobject can find whatever information it needs at run timesuch asits place in the inheritance hierarchy, the size and structure ofits instance variables, and the location of the methodimplementations it can perform in response to messages.


類的例項物件的 isa 指向它的類;類的 isa 指向該類的 metaclass;

類的 super_class 指向其父類,如果該類為根類則值為 NULL;

metaclass 的 isa 指向根 metaclass,如果該 metaclass 是根 metaclass則指向自身;

metaclass 的 super_class 指向父 metaclass,如果該 metaclass 是根 metaclass則指向該 metaclass 對應的類;

Object-C 為每個類的定義生成兩個 objc_class ,一個普通的 class,另一個即metaclass。我們可以在執行期建立這兩個 objc_class 資料結構,然後使用 objc_addClass將 class註冊到執行時系統中,以此實現動態地建立一個新的類。

再深入的學習在下一篇部落格給出。