美文网首页ios
ios 动态创建类

ios 动态创建类

作者: 猪猪9527 | 来源:发表于2018-04-17 09:28 被阅读1次

    //动态创建类

            //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);

    相关文章

      网友评论

        本文标题:ios 动态创建类

        本文链接:https://www.haomeiwen.com/subject/excukftx.html