開源類庫如何使用iOS runtime

開源類庫如何應用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.lxweimin.com/p/ab966e8a82e2#
https://github.com/minggo620/iOSRuntimeLearn

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容