iOS runtimeiOS学习iOS开发攻城狮的集散地

开源类库如何使用iOS runtime

2016-11-25  本文已影响527人  潇潇潇潇潇潇潇

开源类库如何应用iOS runtime的

前言

runtime让Objective-C具有灵活的动态特性,也让Objective-C这门语言具有独特的魅力。关于介绍runtime原理的文章已经很多了,这里不多介绍。我们不妨从实际使用的角度,看看开源类库是如何利用runtime特性实现一些特殊功能,同时也能增加我们对runtime机制的理解和认识。

runtime

C语言中,在编译期决定调用哪个函数,编译完成按顺序调用函数,没有任何二义性。
runtime即运行时机制,它把决定从编译期推迟到运行期,在运行的时候才会确定对象的类型和方法。
Objective-C调用一个方法,如下

[dog eat];

在编译时Objective-C会将它转化为发送消息

objc_msgSend(dog, @selector(eat));

在真正运行的时候才会根据函数的名称找到对应的函数来执行。利用runtime可以在程序运行时动态地修改类和对象的属性方法。

runtime的应用

利用runtime,我们可以做很多事情。如下

  1. 动态交换两个方法的实现(Swizzling)
  2. 为分类添加属性
  3. 获取某个类的所有方法和所有属性

开源类库与runtime

动态交换两个方法的实现

基本使用

引入头号文件<objc/runtime.h>
1.获得某个类的实例方法或类方法

Method originalMethod = class_getInstanceMethod(class, @selector(originalSelector));
Method swizzledMethod = class_getInstanceMethod(class, @selector(swizzledSelector));  
        // 如果要交换类方法,使用下面的方式
        // Method originalMethod = class_getClassMethod(class, originalSelector);
        // Method swizzledMethod = class_getClassMethod(class, swizzledSelector);

2.交换两个方法

method_exchangeImplementations(originalMethod, swizzledMethod);  
实例

MJRefresh是iOS开发中最常用开源类库之一,主要用于UITableView的上拉、下拉刷新功能。MJRefresh有一个功能,它监控它所在的tableview数据的变化,当这个tableview的所有cell数目为0时,隐藏自身。这个功能改写了tableview的reloadData方法,使用runtime将reloadData方法替换为mj_reloadData方法,在mj_reloadData方法中检测当前的tableView的cell数目,并通过block将结果回调给上层。代码如下:

@implementation UITableView (MJRefresh)

+ (void)exchangeInstanceMethod1:(SEL)method1 method2:(SEL)method2
{
    method_exchangeImplementations(class_getInstanceMethod(self, method1), class_getInstanceMethod(self, method2));
}

+ (void)load
{
    [self exchangeInstanceMethod1:@selector(reloadData) method2:@selector(mj_reloadData)];
}

- (void)mj_reloadData
{
    [self mj_reloadData];
    
    [self executeReloadDataBlock];
}

//获取tableview中cell的数量,然后将结果通过block 回调到上层,上层根据所有cell的数目决定是否要隐藏刷新控件
- (void)executeReloadDataBlock
{
    !self.mj_reloadDataBlock ? : self.mj_reloadDataBlock(self.mj_totalDataCount);
}

补充一点,如果originalSelector是父类中的方法,而子类也没有重写它,这时就不能直接交换两个方法的实现,而是要给子类也添加一个originalSelector的实现。
MJRefresh直接操作的是UITableView类,没有继承关系,所以省略了检验reloadData方法,我们在使用方法交换时,保险起见,一般要判断一下,如下所示:
#import <objc/runtime.h>

@implementation UIViewController (Tracking)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];

        SEL originalSelector = @selector(viewWillAppear:);
        SEL swizzledSelector = @selector(xxx_viewWillAppear:);

        Method originalMethod = class_getInstanceMethod(class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);

        // When swizzling a class method, use the following:
        // Class class = object_getClass((id)self);
        // ...
        // Method originalMethod = class_getClassMethod(class, originalSelector);
        // Method swizzledMethod = class_getClassMethod(class, swizzledSelector);

        BOOL didAddMethod =
            class_addMethod(class,
                originalSelector,
                method_getImplementation(swizzledMethod),
                method_getTypeEncoding(swizzledMethod));

        if (didAddMethod) {
            class_replaceMethod(class,
                swizzledSelector,
                method_getImplementation(originalMethod),
                method_getTypeEncoding(originalMethod));
        } else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    });
}

#pragma mark - Method Swizzling

- (void)xxx_viewWillAppear:(BOOL)animated {
    [self xxx_viewWillAppear:animated];
    NSLog(@"viewWillAppear: %@", self);
}

@end

为分类添加属性

基本使用

创建一个类别,在头文件声明一个变量,方便外界调用

@property(nonatomic,copy) NSString *name;

在.m文件中添加属性,其中policy表示存储策略,对应assign、copy、strong

char cName;

-(void)setName:(NSString *) name{
    objc_setAssociatedObject(self, &cName, name, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

-(NSString *)name{
    return objc_getAssociatedObject(self, &cName);
}

使用这个name属性

-(void)printName{
    NSLog(@"My name is %@",self.name);
}  
实例

SDWebImage也是我们常用的开源类库,它的类别UIView+WebCache提供快捷的方式获取图片。由于类别无法添加属性,所以使用runtime为它绑定了一个url属性,方便后续读取。

@implementation UIView (WebCache)

- (nullable NSURL *)sd_imageURL {
    return objc_getAssociatedObject(self, &imageURLKey);
}

- (void)sd_internalSetImageWithURL:(nullable NSURL *)url
                  placeholderImage:(nullable UIImage *)placeholder
                           options:(SDWebImageOptions)options
                      operationKey:(nullable NSString *)operationKey
                     setImageBlock:(nullable SDSetImageBlock)setImageBlock
                          progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
                         completed:(nullable SDExternalCompletionBlock)completedBlock {
......
    objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
......
}

在MJRefresh中,类别UIScrollView+MJRefresh也同样利用runtime,添加了上拉控件和下拉控件属性,代码如下
- (void)setMj_header:(MJRefreshHeader *)mj_header
{
if (mj_header != self.mj_header) {
// 删除旧的,添加新的
[self.mj_header removeFromSuperview];
[self insertSubview:mj_header atIndex:0];

        // 存储新的
        [self willChangeValueForKey:@"mj_header"]; // KVO
        objc_setAssociatedObject(self, &MJRefreshHeaderKey,
                                 mj_header, OBJC_ASSOCIATION_ASSIGN);
        [self didChangeValueForKey:@"mj_header"]; // KVO
    }
}


- (MJRefreshHeader *)mj_header
{
    return objc_getAssociatedObject(self, &MJRefreshHeaderKey);
}

字典转model

基本使用

动态获取类中所有属性,第一个参数表示哪个类,第二个参数放一个接收值的地址,用来存放属性的个数,返回值存放所有获取到的属性

unsigned int count;
Ivar *ivars = class_copyIvarList([Dog class], &count);  

遍历所有取到的属性,取得它们的名字、类型等

const char *varName = ivar_getName(var);
const char *varType = ivar_getTypeEncoding(var);
实例

利用runtime获取所有属性进行字典转model,我们看看开源类库JSONModel是如何做的

 //inspects the class, get's a list of the class properties
-(void)__inspectProperties
{
    //JMLog(@"Inspect class: %@", [self class]);

    NSMutableDictionary* propertyIndex = [NSMutableDictionary dictionary];

    //temp variables for the loops
    Class class = [self class];
    NSScanner* scanner = nil;
    NSString* propertyType = nil;

    // inspect inherited properties up to the JSONModel class
    while (class != [JSONModel class]) {
        //JMLog(@"inspecting: %@", NSStringFromClass(class));

        unsigned int propertyCount;
        objc_property_t *properties = class_copyPropertyList(class, &propertyCount);

        //loop over the class properties
        for (unsigned int i = 0; i < propertyCount; i++) {

            JSONModelClassProperty* p = [[JSONModelClassProperty alloc] init];

            //get property name
            objc_property_t property = properties[i];
            const char *propertyName = property_getName(property);
            p.name = @(propertyName);

            //JMLog(@"property: %@", p.name);

......

            //add the property object to the temp index
            if (p && ![propertyIndex objectForKey:p.name]) {
                [propertyIndex setValue:p forKey:p.name];
            }
        }

        free(properties);

        //ascend to the super of the class
        //(will do that until it reaches the root class - JSONModel)
        class = [class superclass];
    }
}

参考资料:
http://www.jianshu.com/p/ab966e8a82e2#
https://github.com/minggo620/iOSRuntimeLearn

上一篇 下一篇

猜你喜欢

热点阅读