ios动态创建类Class

时间:2023-03-08 17:57:15
ios动态创建类Class

【Objective-C Runtime动态加载】---动态创建类Class

动态创建类Class,动态添加Class成员变量与成员函数,动态变量赋值与取值,动态函数调用等方法

a.使用objc_allocateClassPair创建一个类Class
    const char * className = "Calculator";
    Class kclass = objc_getClass(className);
    if (!kclass) 
    {
       Class superClass = [NSObject class]; 
       kclass = objc_allocateClassPair(superClass, className, 0);
    }

b.使用class_addIvar添加一个成员变量
    NSUInteger size;
    NSUInteger alignment;
    NSGetSizeAndAlignment("*", &size, &alignment);
    class_addIvar(kclass, "expression", size, alignment, "*");

注:
    1.type定义参考:https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html
    2."*"星号代表字符(),iOS字符为4位,并采用4位对齐kclass

c.使用class_addMethod添加成员方法
    class_addMethod(kclass, @selector(setExpressionFormula:), (IMP)setExpressionFormula, "v@:@");
    class_addMethod(kclass, @selector(getExpressionFormula), (IMP)getExpressionFormula, "@@:");

static void setExpressionFormula(id self, SEL cmd, id value)
    {
       NSLog(@"call setExpressionFormula");
    }

static void getExpressionFormula(id self, SEL cmd)
    {
        NSLog(@"call getExpressionFormula");
    }

注:
    1.type定义参考:https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html
    2."v@:@",解释v-返回值void类型,@-self指针id类型,:-SEL指针SEL类型,@-函数第一个参数为id类型
    3."@@:",解释@-返回值id类型,@-self指针id类型,:-SEL指针SEL类型,
d.注册到运行时环境
    objc_registerClassPair(kclass);
e.实例化类
    id instance = [[kclass alloc] init];
f.给变量赋值
   object_setInstanceVariable(instance, "expression", "1+1"); 
g.获取变量值
    void * value = NULL;
    object_getInstanceVariable(instance, "expression", &value); 
h.调用函数
    [instance performSelector:@selector(getExpressionFormula)];