iOS反射機制: objc_property_t的使用

來源:互聯網
上載者:User

標籤:

iOS屬性反射:說白了,就是將兩個對象的所有屬性,用動態方式取出來,並根據屬性名稱,自動綁值。(注意:對象的類,如果是衍生類別,就得靠其他方式來實現了,因為得到不該基類的屬性。)

常用的反射方式,有如下兩種:

從一個自訂實體類->自訂實體類

從一個NSDictionary->自訂實體類(此方式最最常用,如網路Json資料會組成NSDictionary。sqlite查詢資料,可以用第三方組件組成NSDictionary)
直接上碼,(這裡碼在NSObject類別中)
擷取對象所有屬性:
- (NSArray*)propertyKeys

{

    unsigned int outCount, i;

    objc_property_t *properties = class_copyPropertyList([self class], &outCount);

    NSMutableArray *keys = [[NSMutableArray alloc] initWithCapacity:outCount];

    for (i = 0; i < outCount; i++) {

        objc_property_t property = properties[i];

        NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];

        [keys addObject:propertyName];

    }

    free(properties);

    return keys;

}

 

- (BOOL)reflectDataFromOtherObject:(NSObject*)dataSource

{

    BOOL ret = NO;

    for (NSString *key in [self propertyKeys]) {

        if ([dataSource isKindOfClass:[NSDictionary class]]) {

            ret = ([dataSource valueForKey:key]==nil)?NO:YES;

        }

        else

        {

            ret = [dataSource respondsToSelector:NSSelectorFromString(key)];

        }

        if (ret) {

            id propertyValue = [dataSource valueForKey:key];

            //該值不為NSNULL,並且也不為nil

            if (![propertyValue isKindOfClass:[NSNull class]] && propertyValue!=nil) {

                [self setValue:propertyValue forKey:key];

            }           

        }

    }

    return ret;

}

 

/////使用方法
NSDictionary *dicJsonData;

EntityObject *objValue;

[objValue reflectDataFromOtherObject:dicJsonData];  //這樣就可以完成對象的自動賦值了,

 

//你還在使用下面的方法嗎?

objValue.value = [dicJsonData objectForKey:@"value"];

//out了!

iOS反射機制: objc_property_t的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.