[iOS]Objective-C Runtime學(xué)習(xí)筆記之:注冊(cè)類,為類添加成員變量、方法

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);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容