- 相关头文件
#import <objc/runtime.h>
//获取cls中所有成员变量
class_copyIvarList(<#__unsafe_unretained Class cls#>, <#unsigned int *outCount#>)
//获取cls类中所有方法
class_copyMethodList(<#__unsafe_unretained Class cls#>, <#unsigned int *outCount#>)
//获取类方法 +号开头
class_getClassMethod(<#__unsafe_unretained Class cls#>, <#SEL name#>)
//获取实例发放 -号开头
class_getInstanceMethod(<#__unsafe_unretained Class cls#>, <#SEL name#>)
method_exchangeImplementations(<#Method m1#>, <#Method m2#>)
#import <objc/message.h>
objc_msgSend(<#id self#>, <#SEL op, ...#>)
- 功能
2.1 交换两个方法的实现 (要注意是调用实例方法还是类方法)
Method method1 =class_getInstanceMethod([Studentclass],@selector(run)); Method method2 = class_getInstanceMethod([Studentclass], @selector(study)); method_exchangeImplementations(method1, method2); Student *student = [[Studentalloc] init]; [studentrun]; [studentstudy];
2.2 Ios消息方法调用,消息机制
Student *stu = [[Studentalloc] init]; //注意:若报Too many arguments to function call, expected 0, have 3错误,targets->build Setting,搜索msg设置为NO;
objc_msgSend(stu,@selector(setAge:),20); NSLog(@"%d",stu.age);
2.3 遍历类中所有成员变量
//遍历类中所有成员变量 -(void)getIvarList{ unsigned int count=0; Ivar *ivars = class_copyIvarList([Studentclass], &count); NSLog(@"%d---%p",count,ivars); for (int i=0; i<count; i++) { Ivar ivar = ivars[i]; const char *name =ivar_getName(ivar); //变量名称 const char *type =ivar_getTypeEncoding(ivar);//变量类型 NSLog(@"%d - %s - %s",i,name,type); } }
打印结果:
2016-04-19 17:38:30.095 001-RunTime[1732:60419] 0 - _age - i
2016-04-19 17:38:30.095 001-RunTime[1732:60419] 1 - _name - @"NSString"
2016-04-19 17:38:30.095 001-RunTime[1732:60419] 2 - _score - d
Ios 运行时机制
最新推荐文章于 2024-09-05 20:59:16 发布