獲取對象的屬性名、屬性值、屬性特性,協議列表

unsigned int count = 0;
//獲取屬性名
    objc_property_t *properties = class_copyPropertyList([self class], &count);
    for (int i =0; i < count; i ++) {
        const char *propertyName =property_getName(properties[i]);//獲取屬性名
        constchar *propertyAttr =property_getAttributes(properties[i]);//獲取屬性特性  通常是T@"類型"開頭,V_屬性名稱結尾的格式   可以搜索蘋果文檔“Property Attribute Description Examples”
        id propertyValue = [selfvalueForKey:[NSStringstringWithUTF8String:propertyName]];//獲取屬性名對應的值,如果是非對象數據返回NSValue類型
        NSLog(@"name:%@,attr:%@,value:%@",[NSStringstringWithUTF8String:propertyName],[NSStringstringWithUTF8String:propertyAttr],propertyValue);
    }
free(properties);//這裏要對取出來的指針數組進行釋放,不然會有內存泄露
//獲取對象中的變量名
Ivar *vars = class_copyIvarList([self class], &count);
for (int i = 0; i < count; i ++) {
     const char *ivarName = ivar_getName(vars[i]);
     const char *ivarType = ivar_getTypeEncoding(vars[i]);
} 
free(vars);//同樣要釋放
//獲取協議列表
__unsafe_unretained Protocol ** proList= class_copyProtocolList([TestObject class], &count);
    for (int i = 0;  i < count; i ++) {
        Protocol *pro = proList[i];
        const char *name = protocol_getName(pro);//協議名稱
        NSLog(@"%@",[NSString stringWithUTF8String:name]);
    }
    free(proList);
發佈了49 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章