美文网首页
runTime获取属性并解析

runTime获取属性并解析

作者: 傲骨天成科技 | 来源:发表于2021-06-21 17:03 被阅读0次

SFRuntimeModelParent类

@interface SFRuntimeModelParent : NSObject

///
@property (nonatomic, copy) NSString *name;

///
@property (nonatomic, assign) NSInteger age;

///
@property (nonatomic, assign) float height;

///
@property (nonatomic, strong) NSArray *arr;


///
@property (nonatomic, strong) NSObject *child0;
@end

SFRuntimeModelChild类

@interface SFRuntimeModelChild : SFRuntimeModelParent

///
@property (nonatomic, strong) NSString *foot;

@end
/*
     获取父类, 返回Class
     结果:
     ==SFRuntimeModelParent
     */
    Class superClass = class_getSuperclass([SFRuntimeModelChild class]);
    NSLog(@"==%@",superClass);

打印所有属性

/**
     
     结果:
      属性名称0=name
      属性类型0=T@"NSString",C,N,V_name
      属性名称1=age
      属性类型1=Tq,N,V_age
      属性名称2=height
      属性类型2=Tf,N,V_height
      属性名称3=arr
      属性类型3=T@"NSArray",&,N,V_arr
      属性名称4=child0
      属性类型4=T@"NSObject",&,N,V_child0
     */
    unsigned int count = 0;
    
    // 1.得到属性列表
    objc_property_t *properties = class_copyPropertyList([SFRuntimeModelParent class], &count);
    for (int i = 0; i < count; i++) {
        
        // 2.得到单个属性
        objc_property_t property = properties[i];
        
        // 3.得到属性名称
        NSString *propertyName = @(property_getName(property));
        NSLog(@"属性名称%d=%@",i,propertyName);
        
        // 4.得到成员类型
        NSString *attrs = @(property_getAttributes(property));
        NSLog(@"属性类型%d=%@",i,attrs);
    }

属性类型

/**
 *  成员变量类型(属性类型)
 */
NSString *const MJPropertyTypeInt = @"i";
NSString *const MJPropertyTypeShort = @"s";
NSString *const MJPropertyTypeFloat = @"f";
NSString *const MJPropertyTypeDouble = @"d";
NSString *const MJPropertyTypeLong = @"l";
NSString *const MJPropertyTypeLongLong = @"q"; NSInterger
NSString *const MJPropertyTypeChar = @"c";
NSString *const MJPropertyTypeBOOL1 = @"c";
NSString *const MJPropertyTypeBOOL2 = @"b";
NSString *const MJPropertyTypePointer = @"*";

NSString *const MJPropertyTypeIvar = @"^{objc_ivar=}";
NSString *const MJPropertyTypeMethod = @"^{objc_method=}";
NSString *const MJPropertyTypeBlock = @"@?";
NSString *const MJPropertyTypeClass = @"#";
NSString *const MJPropertyTypeSEL = @":";
NSString *const MJPropertyTypeId = @"@"; 对象类型

& 代表strong修饰
C代表copy修饰
N代表noatomic修饰

相关文章

网友评论

      本文标题:runTime获取属性并解析

      本文链接:https://www.haomeiwen.com/subject/qpgyyltx.html