iOS Runtime

weixin_34054866發表於2017-02-12

這篇文章的來源是自己的筆記,因為時間有點久了,所以引用的來源想不起來了,實在不好意思。
引用來源應該也是簡書、csdn、cnblog或者coacoaChina部落格的幾篇文章,我把自己看起來比較有體會,好理解的片段摘錄了一下,望見諒。

  • class_copyPropertyList獲得的是屬性變數,由@property修飾過的變數。

  • class_copyIvarList獲得的是例項變數,包括class_copyPropertyList修飾的以及在m檔案的中@implementation內定義的變數。

//.h

@interface Model : NSObject

@property (nonatomic,copy) NSString *sex;
@property (nonatomic,copy) NSString *name;
@property (nonatomic,assign) NSInteger age;
@property (nonatomic,strong) NSDictionary *imgCode;

@end

//.m


@interface Model ()
@property (nonatomic,copy) NSString *Id;
@end

@implementation Model {
    NSInteger _index;
}

@end

//使用的時候

    unsigned int propertiesCount =0;
    unsigned int ivarsCount =0;
    objc_property_t *properties = class_copyPropertyList(Model, &propertiesCount);
    Ivar *ivars = class_copyIvarList(Model, &ivarsCount);//instance variable

propertiesCount = 5
ivarsCount = 6

遍歷

unsigned int outCount = 0;
Ivar *ivars = class_copyIvarList([object class], &outCount);
for (int i = 0; i < outCount; ++i) {
    // 遍歷取出該類成員變數
    Ivar ivar = ivars[i];
    NSLog(@"\n name = %s  \n type = %s", ivar_getName(ivar), ivar_getTypeEncoding(ivar));
    NSString *columnString = [NSString stringWithUTF8String:ivar_getName(ivar)];
    id value = [object valueForKey: columnString];
}
free(ivars);

相關文章