objective-c runtime practice

1. 获取properties和实例变量

栗子代码:

-------------------------Person.h
@interface Person : NSObject 
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *sex;
- (void)printClass;
- (void)doingHomework;
@end
-------------------------Person.m
@implementation Person{
    NSString *_class;
    NSString *_age;
}
@dynamic name;
-------------------------main.m

unsigned int outCount, i;
id PersonClass=objc_getClass("Person");

objc_property_t *properties=class_copyPropertyList(PersonClass, &outCount);
for (i=0; i<outCount; i++) {
    objc_property_t property=properties[i];
    fprintf(stdout, "Properties: %s\n",property_getName(property));
    
}

Ivar *ivar=class_copyIvarList(PersonClass, &outCount);
for (i=0; i<outCount; i++) {
    Ivar var=ivar[i];
    fprintf(stdout, "Ivars: %s\n",ivar_getName(var));
}

输出

Properties: name
Properties: sex
Ivar: _class
Ivar: _age
Ivar: _sex

我们定义了2个properties:namesex
2个变量:_class_age

但注意到我们的class_copyIvarList仅获取到了3个变量并打印出来了,没有_name,这是由于我们@dynamic修饰了这个property,系统不会为@dynamic修饰的property生成变量

2. Objective-C Associated Objects

runtime系统让objc支持向实例(instance)动态添加对象(object)。

void objc_setAssociatedObject ( id object, const void *key, id value, objc_AssociationPolicy policy );
id objc_getAssociatedObject ( id object, const void *key );
void objc_removeAssociatedObjects ( id object );

那这个功能有什么用呢?最先想到的就是:Category
我们知道category中可以添加方法,但是不能添加实例变量(instance variables),虽然我们可以在interface文件中使用@property申明一个property,语法上没有问题,但编译器不会帮你synthesize任何实例变量,也不会帮你实现getter和setter方法(仅有申明)。
我们可以手动添加getter和setter,但是却没办法增加一个实例变量来存储和跟踪数据变化。

Associated Objects登场,上代码:

-------------------------Person+JobTitle.h
#import "Person.h"
@interface Person (JobTitle)
@property (strong, nonatomic) NSString *jobTitle;
@end
-------------------------Person+JobTitle.m
#import "Person+JobTitle.h"
#import <objc/runtime.h>

static NSString * const KEY=@"associateObjectKey";

@implementation Person (JobTitle)

- (NSString *)jobTitle {
    return objc_getAssociatedObject(self, &KEY);
}

- (void)setJobTitle:(NSString *)jobTitle {
    if ([jobTitle isEqualToString:objc_getAssociatedObject(self, &KEY)]) {
        return;
    } else {
        objc_setAssociatedObject(self, &KEY, jobTitle, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
}
@end
-------------------------main.m
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person *a=[Person new];
        a.jobTitle=@"Programmer: I love Objective-C";
        NSLog(@"jobTitle: %@",[a jobTitle]);
...
}

输出结果

jobTitle: Programmer: I love Objective-C

完美的扩展了实例的属性,而且不用子类化它,通过runtime非常灵活的实现了这个功能。

3. Method Swizzling

通过Method Swizzling我们可以在运行时替换某个Selector的IMP,我们通过下面代码演示一下:

----------------------Person.m
@implementation Person{
    NSString *_class;
    NSString *_age;
}

@dynamic name;

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        SEL originSel=@selector(printClass);
        SEL swizzlingSel=@selector(swizzlingPrint);

        Method originMethod=class_getInstanceMethod(self, originSel);
        Method swizzlingMethod=class_getInstanceMethod(self, swizzlingSel);
        
        method_exchangeImplementations(originMethod, swizzlingMethod);
    });
}

- (void)printClass {
    NSLog(@"[SEL:%@]----but I am printClass",NSStringFromSelector(_cmd));
}

- (void)swizzlingPrint {
    NSLog(@"[SEL:%@]-----but I am swizzlingPrint",NSStringFromSelector(_cmd));
}
----------------------main.m
Person *a=[Person new];
[a printClass];
[a swizzlingPrint];

执行结果

[SEL:printClass]-----but I am swizzlingPrint
[SEL:swizzlingPrint]----but I am printClass

可以看到selector还是原来的selector,但是执行的内容变了。很神奇,这就是runtime消息的魅力,非常灵活。
我们可以通过这个特性,在某些时候替换掉系统的方法实例为自己的。

补充说明:

  • method swizzling最好是放在+(void)load方法中,这个方法从NSObject中继承,这个方法仅会在类或者category在加入runtime时调用一次。即便如此最好也加上dispatch_once,如果method_exchangeImplementations被调用两次就又重新被换回来了,没效果,这个很好理解吧。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转载:http://yulingtianxia.com/blog/2014/11/05/objective-c-r...
    F麦子阅读 772评论 0 2
  • 本文详细整理了 Cocoa 的 Runtime 系统的知识,它使得 Objective-C 如虎添翼,具备了灵活的...
    lylaut阅读 827评论 0 4
  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,789评论 0 9
  • 本文转载自:http://yulingtianxia.com/blog/2014/11/05/objective-...
    ant_flex阅读 799评论 0 1
  • 文中的实验代码我放在了这个项目中。 以下内容是我通过整理[这篇博客] (http://yulingtianxia....
    茗涙阅读 948评论 0 6