Objective-C的运行时常用方法

前言

runtime是OC成为面向对象的基础,了解runtime的基础用法对理解OC非常必要。大量的开源库,如MJExtension,就是使用运行时动态获取类的属性并实现动态赋值。熟悉runtime的方法也是看开源库的基础之一。

一、OC方法篇

OC对象的方法调用是利用selector寻找对应的imp指针进行调用。
现在我们在代码中理解原理。
定义三个函数,该方法名为imp指针

void testFunc1(id self, SEL _cmd) {

NSLog(@"实现testFunc1");

}
void testFunc2(id self, SEL _cmd) {
    
    NSLog(@"实现testFunc2");
    
}
void testFunc3(id self, SEL _cmd) {
    
    NSLog(@"实现testFunc3");
    
}

添加实例方法

//  添加imp到sel,该方法返回一个bool值,成功为YES
    BOOL isAddInstanceMethodFormImpSuccess = class_addMethod(class, sel_registerName("instanceMethod"), (IMP)testFunc1, "v@:");
    if (isAddInstanceMethodFormImpSuccess) {
        NSLog(@"添加imp方法成功");
    }

添加类方法

    BOOL isAddClassMethodFormImpSuccess = class_addMethod(object_getClass(class), sel_registerName("classMethod"), (IMP)testFunc3, "v@:");
    if (isAddClassMethodFormImpSuccess) {
        NSLog(@"添加imp方法成功");
    }

取得blcok的imp指针

  IMP impOfBlock = imp_implementationWithBlock(^(id obj, NSString *string,...){
      NSLog(@"调用者:%@\nstring:%@", obj, string);
  });
  ```
  添加impOfBlock到sel
  BOOL isAddMethodFormImpOfBlockSuccess = class_addMethod(class, sel_registerName("instanceMethodImpOfBlock:"), impOfBlock, "v@:@");
  if (isAddMethodFormImpOfBlockSuccess) {
      NSLog(@"添加impOfBlock方法成功");
  }
  ```

添加方法后,由于这是运行时添加的,我们不能像平时那样调用,要用使用performSelector系列方法进行调用

[object performSelector:@selector(instanceMethod)];
[object performSelector:@selector(instanceMethodImpOfBlock:) withObject:@"我要调用Block"];
[(id)class performSelector:@selector(classMethod)];

使用UIView作为测试类,该viewController的view作为测试对象,该结果为

2016-08-29 00:20:52.404 RuntimeDemo[3515:1637694] 实现testFunc1
2016-08-29 00:20:52.404 RuntimeDemo[3515:1637694] 调用者:<UIView: 0x7ffbdbb04f80; frame = (0 0; 414 736); autoresize = W+H; layer = <CALayer: 0x7ffbdbb03580>>
string:我要调用Block
2016-08-29 00:20:52.405 RuntimeDemo[3515:1637694] 实现testFunc3


##二,成员变量与属性篇
由于在OC在只有在类的创建期间才能添加ivar,但是我们启动app时,类都创建好了,无法添加,所以我在在运行期间自己创建一个类

根据名字取得类
Class testClass = objc_getClass("MLView");
if (!testClass) {
//动态创建类
testClass = objc_allocateClassPair([UIView class], "MLView", 0);
}

添加ivar

BOOL isAddIvarSuccess = class_addIvar(class, "_runtimeString", sizeof(NSString *), log(sizeof(NSString *)), "@"NSString"");
if (isAddIvarSuccess) {
NSLog(@"添加ivar成功");
}

添加property
objc_property_attribute_t type = { "T", "@\"NSString\"" };
 objc_property_attribute_t backingivar  = { "V", "_runtimeString" };
objc_property_attribute_t attrs[] = {type, backingivar};
BOOL isAddPropertySuccess = class_addProperty(class, "runtimeString", attrs, sizeof(attrs)/sizeof(objc_property_attribute_t));
if (isAddPropertySuccess) {
    NSLog(@"添加property成功");
}
 注册类名,并将viewController的view的class设置为运态创建的类(实践上不建议这样做,不易检查错误,如要添加属性可以变相用关联添加,下文用介绍如何在分类添加属性)

objc_registerClassPair(testClass);
//使用view作为 测试对象
id testObject =self.view;
//设置testObject的类,就可以使用动态创建的ivar
object_setClass(testObject, testClass);

添加完变量,成功了一半,现在开始测试是否添加成功就要进行赋值操作

  获取ivar并赋值
Ivar ivar = class_getInstanceVariable(class, "_runtimeString");
object_setIvar(object, ivar, @"addIvar测试字符串");
NSLog(@"addIvar的值:%@", object_getIvar(object, ivar));
  获取property并赋值
objc_property_t property = class_getProperty(class, "runtimeString");
const char *propertyAttr = property_getAttributes(property);
NSLog(@"addProperty的细节:%s", propertyAttr);
[object setValue:@"addProperty测试字符串" forKey:@"_runtimeString"];
NSLog(@"addProperty的值:%@", [object valueForKey:@"_runtimeString"]);
运行后得到的结果为

2016-08-29 00:34:15.870 RuntimeDemo[8155:1663698] addIvar的值:addIvar测试字符串
2016-08-29 00:34:15.870 RuntimeDemo[8155:1663698] addProperty的细节:T@"NSString",V_runtimeString
2016-08-29 00:34:18.211 RuntimeDemo[8155:1663698] addProperty的值:addProperty测试字符串



##三、运行时简单封装
####1、在分类中添加属性
现在我要在给NSObject分类里添加一个对象

@property (nonatomic, strong) NSString *featureIdentifier;

然后重写setter和getter方法,并用关联机制
  • (void)setFeatureIdentifier:(NSString *)featureIdentifier
    {
    objc_setAssociatedObject(self, @selector(featureIdentifier), featureIdentifier, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
  • (NSString *)featureIdentifier
    {
    return objc_getAssociatedObject(self, @selector(featureIdentifier));
    }
####2、获取该类的ivar列表
  • (NSArray *)arrayOfIvars
    {
    unsigned int count = 0;
    Ivar *ivar = class_copyIvarList(self, &count);
    NSMutableArray *ivarNameArray = [[NSMutableArray alloc] init];
    for (int i = 0; i<count; i++) {
    Ivar iva = ivar[i];
    const char *name = ivar_getName(iva);
    NSString *strName = [NSString stringWithUTF8String:name];
    [ivarNameArray addObject:strName];

    }

    free(ivar);
    return ivarNameArray;

}

####3、取得该类属性列表
  • (NSArray *)arrayOfProperties
    {
    unsigned int count = 0;
    objc_property_t *properties = class_copyPropertyList(self, &count);

    NSMutableArray *propertyNameArray = [[NSMutableArray alloc] init];
    for (int i = 0; i<count; i++) {
    objc_property_t property = properties[i];
    const char *name = property_getName(property);
    NSString *strName = [NSString stringWithUTF8String:name];
    [propertyNameArray addObject:strName];

    }

    free(properties);
    return propertyNameArray;

}


####4、取得该类实例方法列表
  • (NSArray *)arrayOfInstanceMethods
    {
    unsigned int count = 0;
    Method *methodList = class_copyMethodList(self, &count);
    NSMutableArray *methods = [[NSMutableArray alloc] init];

    for (NSInteger i = 0; i < count; i++) {
    SEL selector = method_getName(methodList[i]);
    NSString *selString = NSStringFromSelector(selector);
    [methods addObject:selString];
    }

    free(methodList);
    return methods;
    }

####5、取得该类方法方法列表
unsigned int count = 0;
Method *methodList = class_copyMethodList(object_getClass(self), &count);
NSMutableArray *methods = [[NSMutableArray alloc] init];

for (NSInteger i = 0; i < count; i++) {
    SEL selector = method_getName(methodList[i]);
    NSString *methodString = NSStringFromSelector(selector);
    [methods addObject:methodString];
}

free(methodList);
return methods;
####6、取得该类遵循协议列表
  • (NSArray *)arrayOfProtocols{

    unsigned int count = 0;
    Protocol * __unsafe_unretained *protocols = class_copyProtocolList(self, &count);
    NSMutableArray *protocolArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < count; i++) {
    [protocolArray addObject:[NSString stringWithUTF8String:protocol_getName(protocols[i])]];

    }

free(protocols);
return protocolArray;

}

####7、取得该工程所有类的列表
  • (NSArray *)arrayOfAllClass {
    NSMutableArray * classList = [NSMutableArray array];

    unsigned int classesCount = 0;
    Class * classes = objc_copyClassList(&classesCount);

for ( int i = 0; i < classesCount; ++i) {
    NSString *className = NSStringFromClass(classes[i]);

    [classList addObject:className];
}

free(classes);
return classList;

}

####8、取得该对象中有值的的property字典
  • (NSDictionary *)dictionaryOfPropertyKeyValues
    {
    NSArray *properties = [[self class] arrayOfProperties];
    NSMutableDictionary *keyValueDictionary = [[NSMutableDictionary alloc] init];
    for (NSInteger i = 0; i < properties.count; i++) {
    if ([self valueForKey:properties[i]]) {
    [keyValueDictionary setObject:[self valueForKey:properties[i]] forKey:properties[i]];
    }
    }
    return keyValueDictionary;
    }

[此处应该有demo][https://github.com/luomagaoshou/MLRuntimeDemo]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,911评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,014评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 142,129评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,283评论 1 264
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,159评论 4 357
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,161评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,565评论 3 382
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,251评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,531评论 1 292
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,619评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,383评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,255评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,624评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,916评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,199评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,553评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,756评论 2 335

推荐阅读更多精彩内容

  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,670评论 0 9
  • 我们常常会听说 Objective-C 是一门动态语言,那么这个「动态」表现在哪呢?我想最主要的表现就是 Obje...
    Ethan_Struggle阅读 2,161评论 0 7
  • Runtime是一套比较底层的纯C语言API,包含了很多底层的C语言API。在我们平时编写的OC代码中,程序运行时...
    这个年纪的情愫丶阅读 569评论 5 3
  • 听力和单词是硬伤 sad 擦干眼泪 还得继续前进
    不ting下脚步阅读 128评论 0 0
  • 磁性蓝鹰kin235 图表是由App所计算出来的星系印记。我们也可通过计算找出自己的Kin,并且在卓尔金历找到自己...
    ChrisLooi阅读 293评论 0 0