您的位置:首页 > 移动开发 > Objective-C

iOS进阶:Objective-C runtime(一)

2015-10-08 11:33 387 查看
  第一次看到runtime时,觉得太高大上,动态获取方法、属性等简直厉害的不要不要的。在经过查找资料+实践后,发现runtime并没有想象中那么复杂,接下来对runtime进行基本的介绍。

  要使用运行时方法需要引入runtime.h文件

  一、基础知识  

  Method:成员方法

  Ivar:成员变量

  二、常用方法

  class_copyPropertyList:获取属性列表

  class_copyMethodList:获取成员方法列表

  class_copyIvarList:获取成员变量列表

  ivar_getName:获取变量名

  property_getName:获取属性名

  使用示例:

  1.获取成员变量列表

//1.获取变量list
unsignedintivarCount=0;//成员变量数
Ivar*ivarList=class_copyIvarList([selfclass],&ivarCount);//ivar数组

for(inti=0;i<ivarCount;i++){//遍历
Ivarivar=ivarList[i];//获取ivar
constchar*name=ivar_getName(ivar);//获取变量名
NSString*key=[NSStringstringWithUTF8String:name];
NSLog(@"%@",key);

}

      free(ivarList);



  2.获取属性列表

unsignedintcount=0;
objc_property_t*propertList=class_copyPropertyList([selfclass],&count);
for(inti=0;i<count;i++){
objc_property_tproperty=propertList[i];
constchar*name=property_getName(property);
constchar*attrs=property_getAttributes(property);
//property_copyAttributeValue(,)第一个参数为objc_property_t,第二个参数"V"获取变量名,"T"获取类型
constchar*value=property_copyAttributeValue(property,"V");
NSLog(@"name=%s,attrs=%s,value=%s",name,attrs,value);
}

    free(propertList);

  3.获取方法列表 

unsignedintcount=0;
Method*methodList=class_copyMethodList([selfclass],&count);
for(inti=0;i<count;i++){
Methodmethod=methodList[i];
SELselector=method_getName(method);//方法入口
constchar*sel_name=sel_getName(selector);
NSLog(@"方法名%s",sel_name);
}
free(methodList);


  三、使用方向:归档、字典<---->模型、框架封装等

  实现归档

  

#defineWKCodingImplementing\
-(void)encodeWithCoder:(NSCoder*)aCoder\
{\
unsignedintivarCount=0;\
Ivar*ivarList=class_copyIvarList([selfclass],&ivarCount);\
for(inti=0;i<ivarCount;i++){\
Ivarivar=ivarList[i];\
constchar*name=ivar_getName(ivar);\
constchar*type=ivar_getTypeEncoding(ivar);\
NSLog(@"%s-----%s",name,type);\
NSString*key=[NSStringstringWithUTF8String:name];\
idvalue=[selfvalueForKey:key];\
[aCoderencodeObject:valueforKey:key];\
}\
free(ivarList);\
}\
-(nullableinstancetype)initWithCoder:(NSCoder*)aDecoder\
{\
if(self=[superinit]){\
unsignedintivarCount=0;\
Ivar*ivarList=class_copyIvarList([selfclass],&ivarCount);\
for(inti=0;i<ivarCount;i++){\
Ivarivar=ivarList[i];\
constchar*name=ivar_getName(ivar);\
NSString*key=[NSStringstringWithUTF8String:name];\
NSLog(@"%@%@",key,value);\
idvalue=[aDecoderdecodeObjectForKey:key];\
[selfsetValue:valueforKey:key];\
}\
}\
returnself;\
}


 

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: