1.導(dǎo)入工作
#import <objc/runtime.h>
#import <objc/message.h>
2.定義runtime函數(shù)
1.動(dòng)態(tài)創(chuàng)建一個(gè)類,objc_allocateClassPair函數(shù):第一個(gè)參數(shù)是父類。第三個(gè)參數(shù)extraBytes通常指定為0,該參數(shù)是分配給類和元類對(duì)象尾部的索引ivars的字節(jié)數(shù)。
Class People = objc_allocateClassPair([NSObject class], "Person", 0);
2.添加成員變量,第三個(gè)參數(shù),如果變量的類型是指針類型,則傳遞log2(sizeof(pointer_type))。
class_addIvar(People, "_name", sizeof(NSString *), log2(sizeof(NSString *)), @encode(NSString *));
class_addIvar(People, "_age", sizeof(int), sizeof(int), @encode(int));
3.添加方法
//最后一個(gè)參數(shù)為"v@:@“, v:返回void, i:int ,f:double, c:unsigned char等等
SEL sel = sel_registerName("method:");
class_addMethod(People, sel, (IMP)introduction, "v@:@");
4.定義introduction 方法
// class_getInstanceVariable獲取制定名稱的私有變量,kvc取值
void introduction(id self, SEL _cmd, id some) {
NSLog(@"%@,my name is:%@,I'm %@ years old",some,[self valueForKey:@"name"],object_getIvar(self, class_getInstanceVariable([self class], "_age")));
}
5.注冊(cè)類
objc_registerClassPair(People);
6.創(chuàng)建實(shí)例
id peopleInstance = [[People alloc]init];
7.KVC 改變peopleInstance里的實(shí)例變量
[peopleInstance setValue:@"Carrot" forKey:@"name"];
8.用object_setIvar為成員變量賦值
//從類中獲取到成員變量IVar
Ivar age = class_getInstanceVariable(People, "_age");
//為peopleInstance的成員變量賦值
object_setIvar(peopleInstance, age, @22);
9.調(diào)用peopleInstance中的sel的方法
#warning objc_msgSend(peopleInstance, s, @"大家好!");參數(shù)過多報(bào)錯(cuò) 解決:Build Setting–> Apple LLVM 7.0 – Preprocessing–> Enable Strict Checking of objc_msgSend Calls 改為 NO
((void (*)(id, SEL, id))objc_msgSend)(peopleInstance, sel, @"大家好");
10.銷毀
peopleInstance = nil;
objc_disposeClassPair(People);