- 关于class的API
1. object_getClass(instance) //获取isa指向的class
2. object_setClass(instance, [JWStudent class]);//设置isa指向的class
3. object_isClass(id) //判断是否是类对象
4. object_isMetaClass(Class cls) //判断是否是元类对象
5. //动态创建一个类 跟使用
Class newClass = objc_allocateClassPair([NSObject class], "JWCat", 0);
//添加成员变量
class_addIvar(newClass, "_age", sizeof(int), log2(_Alignof(int)), @encode(int));
class_addIvar(newClass, "_weight", sizeof(NSString *), log2(_Alignof(NSString *)), @encode(NSString *));
//添加方法
class_addMethod(newClass, @selector(run), (IMP)test1, "v16@:0");
//注册类
objc_registerClassPair(newClass);
//使用
id cls = [[newClass alloc]init];
//赋值
[cls setValue:@12 forKey:@"_age"];
[cls setValue:@"80kg" forKey:@"_weight"];
[cls run];
NSLog(@"%@----%@",[cls valueForKey:@"_age"],[cls valueForKey:@"_weight"]);
6.拷贝成员变量列表
JWPerson * p = [JWPerson new];
unsigned int count;
Ivar * ivars = class_copyIvarList([JWPerson class], &count);
for (int i = 0 ; i< count; i++) {
Ivar ivar = ivars[i];
NSLog(@"%s----%s",ivar_getName(ivar),ivar_getTypeEncoding(ivar));
}
free(ivars);
- 交换方法API
class_replaceMethod(Class cls,IMP imp,const char *types);
//交换方法
Method m1 = class_getInstanceMethod([JWPerson class], @selector(print));
Method m2 = class_getInstanceMethod([JWPerson class], @selector(test));
method_exchangeImplementations(m1, m2);
JWPerson * p = [JWPerson new];
[p print];
[p test];
网友评论