//动态创建类
//1.使用objc_allocateClassPair创建一个类Class
const char *className = "Person";
Class class = objc_getClass(className);
if(!class){
Class superClass = [NSObject class];
class = objc_allocateClassPair(superClass, className, 0);
}
//2.现在可以使用自定义的Person类
id instance = [[class alloc] init];
//3.给instance类添加一个属性name,并且赋值
objc_setAssociatedObject(instance, "name", @"Victor John", OBJC_ASSOCIATION_COPY_NONATOMIC);
//给description属性设置
objc_setAssociatedObject(instance, "description", @"Person类的description", OBJC_ASSOCIATION_COPY_NONATOMIC);
//4.然后获取值
id name = objc_getAssociatedObject(instance, "name");
id description = objc_getAssociatedObject(instance, "description");
//5.输出打印
NSLog(@"Person=%p, name=%@ ,description=%@", class, name, description);
网友评论