ObjC 學(xué)習(xí)筆記(三):property

在我們將JSON數(shù)據(jù)轉(zhuǎn)換為Model過程中婿失,我們常常會使用MJExtension或者JSONModel等框架,那他們的實(shí)現(xiàn)和在runtime中都是怎么去實(shí)現(xiàn)的呢辆憔?

首先渣蜗,我們做一個簡化版的JSON轉(zhuǎn)Model

// 定義Model
@interface Product : NSObject

@property (nonatomic, copy) NSString *productId;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) double price;

@end


@implementation Product

- (NSString *)description {
    return [NSString stringWithFormat:@"productId: %@, name: %@, price: %f", _productId, _name, _price];
}

@end


// 實(shí)現(xiàn)最基本的JSON轉(zhuǎn)Model县遣,不考慮類型匹配等問題
- (void)json2Model:(NSDictionary *)dict {
    
    Product *product = [[Product alloc] init];
    
    unsigned int propertyCount;
    objc_property_t *properties = class_copyPropertyList([Product class], &propertyCount);
    for (int idx = 0; idx < propertyCount; idx ++) {
        objc_property_t property = properties[idx];
        const char *name = property_getName(property);
        
        id value = dict[@(name)];
        [product setValue:value forKey:@(name)];
    }
    
    NSLog(@"product : %@", product);    
}

我們從上面的代碼中糜颠,可以找到實(shí)現(xiàn)這個功能的兩和個方法class_copyPropertyListproperty_getName,下面我們從class_copyPropertyList開始學(xué)習(xí)屬性相關(guān)的內(nèi)容萧求。

class_copyPropertyList

接下來其兴,我們看一下class_copyPropertyList的實(shí)現(xiàn)

objc_property_t *
class_copyPropertyList(Class cls, unsigned int *outCount)
{
    if (!cls) {
        if (outCount) *outCount = 0;
        return nil;
    }

    mutex_locker_t lock(runtimeLock);

    checkIsKnownClass(cls);
    assert(cls->isRealized());
    
    // 從類中的定義中找到相關(guān)數(shù)據(jù),`class->data()`會返回函數(shù)夸政、變量元旬、協(xié)議等信息
    auto rw = cls->data();

    property_t **result = nil;
    
    // 獲取變量數(shù)量
    unsigned int count = rw->properties.count();
    if (count > 0) {
          // 分配內(nèi)存空間
        result = (property_t **)malloc((count + 1) * sizeof(property_t *));

        count = 0;
        
        // 遍歷變量,存儲到結(jié)果數(shù)據(jù)數(shù)組中
        for (auto& prop : rw->properties) {
            result[count++] = &prop;
        }
        result[count] = nil;
    }

    if (outCount) *outCount = count;
    return (objc_property_t *)result;
}

上面注釋中我們給幾個關(guān)鍵節(jié)點(diǎn)添加了注釋,我們可以清晰的看到函數(shù)匀归、變量坑资、協(xié)議等信息都是由cls->data()這個函數(shù)返回的,我們進(jìn)一步的去了解變量在類結(jié)構(gòu)中是如何存儲的穆端。

objc_class中盐茎,我們可以看到變量等都是使用bits.data()獲取相關(guān)內(nèi)容。

struct objc_class : objc_object {

    class_data_bits_t bits;    // class_rw_t * plus custom rr/alloc flags
    class_rw_t *data() { 
        return bits.data();
    }

    ....
}

從上述描述中我們可以了解到變量的存儲結(jié)構(gòu)objc_class.bits.data()->properties徙赢。

在了解class_copyPropertyList之后字柠,我們再來看看其他與變量相關(guān)的方法。

property_getName 和 property_getAttributes

property_getNameproperty_getAttributes從命名上我們可以看出狡赐,這兩個方法是用于獲取變量的名字和類型窑业。

我們接下來先看一下property_t的定義,這個結(jié)構(gòu)中只有nameattributes兩個屬性枕屉,分別存儲了名字和類型常柄。

struct property_t {
    const char *name;
    const char *attributes;
};

然后我們使用property_getNameproperty_getAttributes兩個方法就可以輕松的獲取到變量的信息,具體實(shí)現(xiàn)如下:

const char *name = property_getName(property);
const char *attr = property_getAttributes(property);

property_copyAttributeList

這個方法并不是我們常用的方法搀擂,我們只需要大致了解一下他的實(shí)現(xiàn)即可西潘。

// 外部調(diào)用方法
objc_property_attribute_t *property_copyAttributeList(objc_property_t prop, 
                                                      unsigned int *outCount)
{
    if (!prop) {
        if (outCount) *outCount = 0;
        return nil;
    }

    mutex_locker_t lock(runtimeLock);
    return copyPropertyAttributeList(prop->attributes,outCount);
}

// 內(nèi)部實(shí)現(xiàn)方法
objc_property_attribute_t *
copyPropertyAttributeList(const char *attrs, unsigned int *outCount)
{
    if (!attrs) {
        if (outCount) *outCount = 0;
        return nil;
    }

    // Result size:
    //   number of commas plus 1 for the attributes (upper bound)
    //   plus another attribute for the attribute array terminator
    //   plus strlen(attrs) for name/value string data (upper bound)
    //   plus count*2 for the name/value string terminators (upper bound)
    unsigned int attrcount = 1;
    const char *s;
    for (s = attrs; s && *s; s++) {
        if (*s == ',') attrcount++;
    }

    size_t size = 
        attrcount * sizeof(objc_property_attribute_t) + 
        sizeof(objc_property_attribute_t) + 
        strlen(attrs) + 
        attrcount * 2;
    objc_property_attribute_t *result = (objc_property_attribute_t *) 
        calloc(size, 1);

    objc_property_attribute_t *ra = result;
    char *rs = (char *)(ra+attrcount+1);

    attrcount = iteratePropertyAttributes(attrs, copyOneAttribute, &ra, &rs);

    assert((uint8_t *)(ra+1) <= (uint8_t *)result+size);
    assert((uint8_t *)rs <= (uint8_t *)result+size);

    if (attrcount == 0) {
        free(result);
        result = nil;
    }

    if (outCount) *outCount = attrcount;
    return result;
}

從上面的代碼我們可以看到在實(shí)現(xiàn)文件里面將屬性拆分為T, C, N, V,分別對應(yīng)屬性的類型,copy, nonatomic, 屬性名稱哨颂, 并輸出位一個objc_property_attribute_t * 數(shù)組保存屬性信息喷市。

property_copyAttributeValue

property_copyAttributeValue也不是一個常用的方法,我們可以通過T, C, N, V獲取屬性中對應(yīng)的值威恼。

char *copyPropertyAttributeValue(const char *attrs, const char *name)
{
    char *result = nil;

    iteratePropertyAttributes(attrs, findOneAttribute, (void*)name, &result);

    return result;
}

class_addProperty 和 class_replaceProperty

這兩個方法用于修改和替換屬性品姓,最后都使用_class_addProperty方法進(jìn)行操作,通過bool replace區(qū)分是添加變量或者修改變量箫措。

_class_addProperty(Class cls, const char *name, 
                   const objc_property_attribute_t *attrs, unsigned int count, 
                   bool replace)
{
    if (!cls) return NO;
    if (!name) return NO;

    // 判斷屬性是否存在腹备,如果屬性存在則無法添加
    property_t *prop = class_getProperty(cls, name);
    if (prop  &&  !replace) {
        // already exists, refuse to replace
        return NO;
    } 
    else if (prop) {
        // replace existing
        mutex_locker_t lock(runtimeLock);
        try_free(prop->attributes);
        // 通過`copyPropertyAttributeString`方法生成變量替換的變量
        prop->attributes = copyPropertyAttributeString(attrs, count);
        return YES;
    }
    else {
        mutex_locker_t lock(runtimeLock);
        
        assert(cls->isRealized());
        
        property_list_t *proplist = (property_list_t *)
            malloc(sizeof(*proplist));
        proplist->count = 1;
        proplist->entsizeAndFlags = sizeof(proplist->first);
        proplist->first.name = strdupIfMutable(name);
        // 通過`copyPropertyAttributeString`方法生成變量替換的變量
        proplist->first.attributes = copyPropertyAttributeString(attrs, count);
        
        cls->data()->properties.attachLists(&proplist, 1);
        
        return YES;
    }
}

總結(jié)

property_t可以幫助我們動態(tài)的獲取和修改類的變量,最常是用的就是在JSON與Model互轉(zhuǎn)斤蔓,比較知名的就有JSONModelMJExtension植酥,我們可以通過閱讀這些成熟的框架來了解更多關(guān)于property_t的使用。

更好的閱讀體驗可以參考個人網(wǎng)站:https://zevwings.com

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末弦牡,一起剝皮案震驚了整個濱河市友驮,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌喇伯,老刑警劉巖喊儡,帶你破解...
    沈念sama閱讀 219,490評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件拨与,死亡現(xiàn)場離奇詭異稻据,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評論 3 395
  • 文/潘曉璐 我一進(jìn)店門捻悯,熙熙樓的掌柜王于貴愁眉苦臉地迎上來匆赃,“玉大人,你說我怎么就攤上這事今缚∷懔” “怎么了?”我有些...
    開封第一講書人閱讀 165,830評論 0 356
  • 文/不壞的土叔 我叫張陵姓言,是天一觀的道長瞬项。 經(jīng)常有香客問我,道長何荚,這世上最難降的妖魔是什么囱淋? 我笑而不...
    開封第一講書人閱讀 58,957評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮餐塘,結(jié)果婚禮上妥衣,老公的妹妹穿的比我還像新娘。我一直安慰自己戒傻,他們只是感情好税手,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評論 6 393
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著需纳,像睡著了一般芦倒。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上不翩,一...
    開封第一講書人閱讀 51,754評論 1 307
  • 那天熙暴,我揣著相機(jī)與錄音,去河邊找鬼慌盯。 笑死周霉,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的亚皂。 我是一名探鬼主播俱箱,決...
    沈念sama閱讀 40,464評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼灭必!你這毒婦竟也來了狞谱?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤禁漓,失蹤者是張志新(化名)和其女友劉穎跟衅,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體播歼,經(jīng)...
    沈念sama閱讀 45,847評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡伶跷,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片叭莫。...
    茶點(diǎn)故事閱讀 40,137評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡蹈集,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出雇初,到底是詐尸還是另有隱情拢肆,我是刑警寧澤,帶...
    沈念sama閱讀 35,819評論 5 346
  • 正文 年R本政府宣布靖诗,位于F島的核電站郭怪,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏刊橘。R本人自食惡果不足惜移盆,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望伤为。 院中可真熱鬧咒循,春花似錦、人聲如沸绞愚。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽位衩。三九已至裆蒸,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間糖驴,已是汗流浹背僚祷。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留贮缕,地道東北人辙谜。 一個月前我還...
    沈念sama閱讀 48,409評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像感昼,于是被迫代替她去往敵國和親装哆。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評論 2 355

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