iOS runtime探究(三): 從runtime開(kāi)始理解OC的屬性property

你要知道的runtime都在這里

轉(zhuǎn)載請(qǐng)注明出處 http://www.lxweimin.com/p/0623addb6b74

本文主要講解runtime相關(guān)知識(shí),從原理到實(shí)踐,由于包含內(nèi)容過(guò)多分為以下五篇文章詳細(xì)講解,可自行選擇需要了解的方向:

本文是系列文章的第三篇文章從runtime開(kāi)始: 理解OC的屬性property,主要從runtime出發(fā)講解屬性property相關(guān)的底層實(shí)現(xiàn)和相關(guān)方法,由于之前的博客已經(jīng)詳細(xì)講解了property的底層實(shí)現(xiàn),所以本文不再贅述,如有需要可以查看相關(guān)文章:iOS @property探究(一): 基礎(chǔ)詳解該文主要講解property的基礎(chǔ)以及修飾符詳解,iOS @property探究(二): 深入理解該文主要深入代碼理解property的底層實(shí)現(xiàn),由于與本文的內(nèi)容由很大的重復(fù),因此本文不再贅述上述相關(guān)內(nèi)容。

本文將會(huì)講解一些runtime操作屬性的相關(guān)方法。

首先回顧一下相關(guān)代碼以及與property底層實(shí)現(xiàn)相關(guān)的兩個(gè)結(jié)構(gòu)體:

//OC自定義類(lèi)的定義
@interface Person : NSObject

@property (nonatomic, copy) NSString* cjmName;
@property (nonatomic, assign) NSUInteger cjmAge;

@end

@implementation Person

@synthesize cjmName = _cjmName;
@synthesize cjmAge = _cjmAge;

@end


//clang轉(zhuǎn)寫(xiě)為.cpp的相關(guān)代碼
struct _prop_t {
        const char *name;
        const char *attributes;
};

static struct /*_prop_list_t*/ {
        unsigned int entsize;  // sizeof(struct _prop_t)
        unsigned int count_of_properties;
        struct _prop_t prop_list[2];
} _OBJC_$_PROP_LIST_Person __attribute__ ((used, section ("__DATA,__objc_const"))) = {
        sizeof(_prop_t),
        2,
        {{"cjmName","T@\"NSString\",C,N,V_cjmName"},
        {"cjmAge","TQ,N,V_cjmAge"}}
};

通過(guò)上述代碼其實(shí)我們可以看出,一個(gè)@property屬性在底層就是一個(gè)結(jié)構(gòu)體描述,那么我們?nèi)绾潍@取這個(gè)結(jié)構(gòu)體呢?可以通過(guò)如下代碼獲取:

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person* p = [[Person alloc] init];
        p.cjmName = @"Jiaming Chen";
        
        unsigned int propertyCount = 0;
        objc_property_t *propertyList = class_copyPropertyList([p class], &propertyCount);
        for (int i = 0; i < propertyCount; i++) {
            const char* name = property_getName(propertyList[i]);
            const char* attributes = property_getAttributes(propertyList[i]);
            NSLog(@"%s %s", name, attributes);
        }
    }
    return 0;
}

首先看一下objc_property_t是什么,在objc/runtime.h中可以找到相關(guān)定義:

typedef struct objc_property *objc_property_t;

它是一個(gè)指向結(jié)構(gòu)體struct objc_property的指針,這里的結(jié)構(gòu)體struct objc_property其實(shí)就是前文中.cpp文件中的struct _prop_t結(jié)構(gòu)體,通過(guò)class_copyPropertyList方法就可以獲取到相關(guān)類(lèi)的所有屬性,具體函數(shù)聲明如下:

/** 
 * Describes the properties declared by a class.
 * 
 * @param cls The class you want to inspect.
 * @param outCount On return, contains the length of the returned array. 
 *  If \e outCount is \c NULL, the length is not returned.        
 * 
 * @return An array of pointers of type \c objc_property_t describing the properties 
 *  declared by the class. Any properties declared by superclasses are not included. 
 *  The array contains \c *outCount pointers followed by a \c NULL terminator. You must free the array with \c free().
 * 
 *  If \e cls declares no properties, or \e cls is \c Nil, returns \c NULL and \c *outCount is \c 0.
 */
OBJC_EXPORT objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0);

通過(guò)注釋可以看出,第一個(gè)參數(shù)是相關(guān)類(lèi)的類(lèi)對(duì)象(如有疑問(wèn)可以查閱本系列文章的前兩篇文章),第二個(gè)參數(shù)是一個(gè)指向unsigned int的指針,用于指明property的數(shù)量,通過(guò)該方法就能夠獲取到所有的屬性,接下來(lái)可以通過(guò)property_getNameproperty_getAttributes方法獲取該屬性描述的nameattributes值,輸出的結(jié)果如下:

2017-03-27 09:59:20.914487 OCTest[2467:460742] cjmName T@"NSString",C,N,V_cjmName
2017-03-27 09:59:20.915321 OCTest[2467:460742] cjmAge TQ,N,V_cjmAge

name很好理解,后面的attributes通過(guò)對(duì)比不難發(fā)現(xiàn)其規(guī)律,感興趣的讀者也可以多設(shè)置幾個(gè)不同類(lèi)型、不同修飾符的property看一下輸出。

除此之外哈有一下幾個(gè)方法用于根據(jù)屬性名獲取一個(gè)屬性描述結(jié)構(gòu)體、添加屬性、替換屬性等方法。

/** 
 * Returns a property with a given name of a given class.
 * 
 * @param cls The class you want to inspect.
 * @param name The name of the property you want to inspect.
 * 
 * @return A pointer of type \c objc_property_t describing the property, or
 *  \c NULL if the class does not declare a property with that name, 
 *  or \c NULL if \e cls is \c Nil.
 */
OBJC_EXPORT objc_property_t class_getProperty(Class cls, const char *name)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0);
    
/** 
 * Adds a property to a class.
 * 
 * @param cls The class to modify.
 * @param name The name of the property.
 * @param attributes An array of property attributes.
 * @param attributeCount The number of attributes in \e attributes.
 * 
 * @return \c YES if the property was added successfully, otherwise \c NO
 *  (for example, the class already has that property).
 */
OBJC_EXPORT BOOL class_addProperty(Class cls, const char *name, const objc_property_attribute_t *attributes, unsigned int attributeCount)
    OBJC_AVAILABLE(10.7, 4.3, 9.0, 1.0);

/** 
 * Replace a property of a class. 
 * 
 * @param cls The class to modify.
 * @param name The name of the property.
 * @param attributes An array of property attributes.
 * @param attributeCount The number of attributes in \e attributes. 
 */
OBJC_EXPORT void class_replaceProperty(Class cls, const char *name, const objc_property_attribute_t *attributes, unsigned int attributeCount)
    OBJC_AVAILABLE(10.7, 4.3, 9.0, 1.0);

舉個(gè)簡(jiǎn)單的栗子:

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person* p = [[Person alloc] init];
        p.cjmAge = 20;
        p.cjmName = @"Jiaming Chen";
        
        unsigned int propertyCount = 0;
        objc_property_t *propertyList = class_copyPropertyList([p class], &propertyCount);
        for (int i = 0; i < propertyCount; i++) {
            const char* name = property_getName(propertyList[i]);
            const char* attributes = property_getAttributes(propertyList[i]);
            NSLog(@"%s %s", name, attributes);
        }
        objc_property_attribute_t attributes = {
            "T@\"NSString\",C,N,V_studentIdentifier",
            "",
        };
        class_addProperty([p class], "studentIdentifier", &attributes, 1);
        objc_property_t property = class_getProperty([p class], "studentIdentifier");
        NSLog(@"%s %s", property_getName(property), property_getAttributes(property));
    }
    return 0;
}

通過(guò)上述方法就能添加一個(gè)屬性,由于本人水平有限實(shí)際開(kāi)發(fā)中沒(méi)有用過(guò)上述方法,具體實(shí)際例子也舉不出來(lái)所以不再過(guò)多贅述。

備注

由于作者水平有限,難免出現(xiàn)紕漏,如有問(wèn)題還請(qǐng)不吝賜教。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,606評(píng)論 6 533
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,582評(píng)論 3 418
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人,你說(shuō)我怎么就攤上這事?!?“怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 176,540評(píng)論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀(guān)的道長(zhǎng)。 經(jīng)常有香客問(wèn)我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 63,028評(píng)論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,801評(píng)論 6 410
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 55,223評(píng)論 1 324
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,294評(píng)論 3 442
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 42,442評(píng)論 0 289
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,976評(píng)論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,800評(píng)論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,996評(píng)論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,543評(píng)論 5 360
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,233評(píng)論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 34,662評(píng)論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 35,926評(píng)論 1 286
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,702評(píng)論 3 392
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,991評(píng)論 2 374

推薦閱讀更多精彩內(nèi)容