void newFunction(id self,SEL _cmp,NSString *string){
NSLog(@"string = %@",string);
}
参数说明:
cls:被添加方法的类
name:可以理解为方法名,这个貌似随便起名,比如我们这里叫sayHello2
imp:实现这个方法的函数
types:一个定义该函数返回值类型和参数类型的字符串,这个具体会在后面讲
其中types参数为"i@:@“,按顺序分别表示:
i:返回值类型int,若是v则表示void
@:参数id(self)
::SEL(_cmd)
@:id(str)
这些表示方法都是定义好的(Type Encodings),关于Type Encodings的其他类型定义请参考官方文档
最后调用say:方法:
2:获取所有的属性包括定义在{}里面的
Ivar*vaaa=class_copyIvarList(<#__unsafe_unretained Class cls#>, <#unsigned int *outCount#>)
参数说明:第一个是类名 第二个是该类的所有属性的总数目具体用法如下
unsigned int count = 0;
//获取一个类当中所有的成员变量的值和类型
Ivar *varArr=class_copyIvarList([Student class], &count);
for (NSInteger i=0; i<count; i++) {
Ivar var=varArr[i];
NSString*name=[NSString stringWithCString:ivar_getName(var) encoding:NSUTF8StringEncoding];
NSString*typ=[NSString stringWithCString:ivar_getTypeEncoding(var) encoding:NSUTF8StringEncoding];
NSLog(@"name=%@\n type=%@\n",name,typ);
}
Student*student=[Student new];
Ivar var=varArr[0];
Ivar varId=varArr[1];
object_setIvar(student, var, @"xiaoming");
object_setIvar(student, varId, @"3112002956");
NSLog(@"name=%@\nID=%@\n",student.name,student.ID);
3:获取所有的方法包括属性的get方法和set方法
unsigned int count=0;
Method*methodArr=class_copyMethodList([Student class], &count);
for (NSInteger i=0; i<count; i++) {
Method method=methodArr[i];
//返回SEL方法选择器当中包含的方法名
//NSStringFromSelector->反射
SEL selector=method_getName(method);
NSString*methodName=NSStringFromSelector(selector);
NSLog(@"methodName%@",methodName);
}
Student*student=[Student new];
//强制执行方法
[studentperformSelector:@selector(loveMoney)];
Method method = class_getInstanceMethod([Student class], @selector(loveMoney));
//修改方法的实现
method_setImplementation(method, (IMP)function1);
Student *student = [Student new];
//强制调用
[student performSelector:@selector(loveMoney)];
具体为什么要写这两个参数还想不明白
void function1(id self,SEL _cmp){
NSLog(@"%s",__func__);
}