【Objective-C Runtime動態載入】 動態創建類Class 動態創建類Class,動態添加Class成員變數與成員函數,動態變數賦值與取值,動態函數調用等方法 a.使用objc_allocateClassPair創建一個類Class const char * className = " ...
【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)];