iOS Runtime的實際應用

iOS Runtime的實際應用

導入

見題知意,這篇文章并不是告訴你什么是Runtime機制以及它的原理,本文主要講的是runtime在實際開發過程中的應用,如果想要了解runtime機制的實現原理,我建議看這篇文章,這邊文章詳細地講解了iOSRuntime的原理(看完必須清楚isa指針以及消息轉發機制的原理)。

Runtime的實際應用

1、動態給分類添加屬性

這個應該使用的比較頻繁,通過runtime動態添加屬性,可以給系統類添加自定義屬性,靈活使用,可以帶來神奇的效果。

//(block直接調用手勢的action)
+ (instancetype)mm_gestureRecognizerWithActionBlock:(MMGestureBlock)block {
    __typeof(self) weakSelf = self;
    return [[weakSelf alloc]initWithActionBlock:block];
}
- (instancetype)initWithActionBlock:(MMGestureBlock)block {
    self = [self init];
    [self addActionBlock:block];
    [self addTarget:self action:@selector(invoke:)];
    return self;
}

- (void)addActionBlock:(MMGestureBlock)block {
    if (block) {
        objc_setAssociatedObject(self, &target_key, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
    }
}
- (void)invoke:(id)sender {
    MMGestureBlock block = objc_getAssociatedObject(self, &target_key);
    if (block) {
        block(sender);
    }
}

2、方法的交換swizzling

這個方法,一般在特殊的情況下使用,可以將系統的方法轉換成自定義的方法,在一些特殊的場景,比如iOS的平板開發及手機開發代碼整合時,使用起來比較方便。

@implementation UIImage (hook)

+ (void)load {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        Class selfClass = object_getClass([self class]);
        
        SEL oriSEL = @selector(imageNamed:);
        Method oriMethod = class_getInstanceMethod(selfClass, oriSEL);
        
        SEL cusSEL = @selector(myImageNamed:);
        Method cusMethod = class_getInstanceMethod(selfClass, cusSEL);
        
        BOOL addSucc = class_addMethod(selfClass, oriSEL, method_getImplementation(cusMethod), method_getTypeEncoding(cusMethod));
        if (addSucc) {
            class_replaceMethod(selfClass, cusSEL, method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));
        }else {
            method_exchangeImplementations(oriMethod, cusMethod);
        }
        
    });
}
+ (UIImage *)myImageNamed:(NSString *)name {
    
    NSString * newName = [NSString stringWithFormat:@"%@%@", @"new_", name];
    return [self myImageNamed:newName];
}

3、字典轉模型

這個很常見,網上所有的字典轉模型的三方框架最底層的實現原理莫過于此,你們去看一下就會明白了,比如MJExtension。

const char *kPropertyListKey = "YFPropertyListKey";
+ (NSArray *)yf_objcProperties
{
    /* 獲取關聯對象 */
    NSArray *ptyList = objc_getAssociatedObject(self, kPropertyListKey);
    /* 如果 ptyList 有值,直接返回 */
    if (ptyList) {
        return ptyList;
    }
    /* 調用運行時方法, 取得類的屬性列表 */
    /* 成員變量:
     * class_copyIvarList(__unsafe_unretained Class cls, unsigned int *outCount)
     * 方法:
     * class_copyMethodList(__unsafe_unretained Class cls, unsigned int *outCount)
     * 屬性:
     * class_copyPropertyList(__unsafe_unretained Class cls, unsigned int *outCount)
     * 協議:
     * class_copyProtocolList(__unsafe_unretained Class cls, unsigned int *outCount)
     */
    unsigned int outCount = 0;
    /**
     * 參數1: 要獲取得類
     * 參數2: 類屬性的個數指針
     * 返回值: 所有屬性的數組, C 語言中,數組的名字,就是指向第一個元素的地址
     */
    /* retain, creat, copy 需要release */
    objc_property_t *propertyList = class_copyPropertyList([self class], &outCount);
    NSMutableArray *mtArray = [NSMutableArray array];
    /* 遍歷所有屬性 */
    for (unsigned int i = 0; i < outCount; i++) {
        /* 從數組中取得屬性 */
        objc_property_t property = propertyList[i];
        /* 從 property 中獲得屬性名稱 */
        const char *propertyName_C = property_getName(property);
        /* 將 C 字符串轉化成 OC 字符串 */
        NSString *propertyName_OC = [NSString stringWithCString:propertyName_C encoding:NSUTF8StringEncoding];
        [mtArray addObject:propertyName_OC];
    }
    /* 設置關聯對象 */
    /**
     *  參數1 : 對象self
     *  參數2 : 動態添加屬性的 key
     *  參數3 : 動態添加屬性值
     *  參數4 : 對象的引用關系
     */
    objc_setAssociatedObject(self, kPropertyListKey, mtArray.copy, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    /* 釋放 */
    free(propertyList);
    return mtArray.copy;
}
+ (instancetype)modelWithDict:(NSDictionary *)dict {
    /* 實例化對象 */
    id objc = [[self alloc]init];
    /* 使用字典,設置對象信息 */
    /* 1. 獲得 self 的屬性列表 */
    NSArray *propertyList = [self  yf_objcProperties];
    /* 2. 遍歷字典 */
    [dict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        /* 3. 判斷 key 是否字 propertyList 中 */
        if ([propertyList containsObject:key]) {
            /* 說明屬性存在,可以使用 KVC 設置數值 */
            [objc setValue:obj forKey:key];
        }
    }];
    /* 返回對象 */
    return objc;
}

4、獲取所有的私有屬性和方法

這個在判斷是否子類重寫了父類的方法時會用到。

#pragma mark - 獲取所有的屬性(包括私有的)
- (void)getAllIvar {
    unsigned int count = 0;
    //Ivar:定義對象的實例變量,包括類型和名字。
    //獲取所有的屬性(包括私有的)
    Ivar *ivars= class_copyIvarList([UIPageControl class], &count);
    for (int i = 0; i < count; i++) {
        //取出成員變量
        Ivar ivar = ivars[i];
        
        NSString *name = [NSString stringWithUTF8String:ivar_getName(ivar)];
        NSString *type = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
        NSLog(@"屬性 --> %@ 和 %@",name,type);
        
    }
    
}
#pragma mark - 獲取所有的方法(包括私有的)
- (void)getAllMethod {
    unsigned int count = 0;
    //獲取所有的方法(包括私有的)
    Method *memberFuncs = class_copyMethodList([UIPageControl class], &count);
    for (int i = 0; i < count; i++) {
        
        SEL address = method_getName(memberFuncs[i]);
        NSString *methodName = [NSString stringWithCString:sel_getName(address) encoding:NSUTF8StringEncoding];
        
        NSLog(@"方法 : %@",methodName);
    }
    
}


5、對私有屬性修改

好像沒遇到過具體需要使用地方。

#pragma mark - 對私有變量的更改
- (void)changePrivate {
    Person *onePerson = [[Person alloc] init];
    NSLog(@"Person屬性 == %@",[onePerson description]);
    
    unsigned  int count = 0;
    Ivar *members = class_copyIvarList([Person class], &count);
    
    for (int i = 0; i < count; i++){
        Ivar var = members[i];
        const char *memberAddress = ivar_getName(var);
        const char *memberType = ivar_getTypeEncoding(var);
        NSLog(@"獲取所有屬性 = %s ; type = %s",memberAddress,memberType);
    }
    //對私有變量的更改
    Ivar m_address = members[1];
    object_setIvar(onePerson, m_address, @"上海");
    NSLog(@"對私有變量的(地址)進行更改 : %@",[onePerson description]);
    
}

6、歸檔:解檔

快速定義歸檔和解檔屬性

@implementation MMModel

- (void)encodeWithCoder:(NSCoder *)encoder {
    unsigned int count = 0;
    //  利用runtime獲取實例變量的列表
    Ivar *ivars = class_copyIvarList([self class], &count);
    for (int i = 0; i < count; i ++) {
        //  取出i位置對應的實例變量
        Ivar ivar = ivars[i];
        //  查看實例變量的名字
        const char *name = ivar_getName(ivar);
        //  C語言字符串轉化為NSString
        NSString *nameStr = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
        //  利用KVC取出屬性對應的值
        id value = [self valueForKey:nameStr];
        //  歸檔
        [encoder encodeObject:value forKey:nameStr];
    }
    
    //  記住C語言中copy出來的要進行釋放
    free(ivars);
    
}

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        unsigned int count = 0;
        Ivar *ivars = class_copyIvarList([self class], &count);
        for (int i = 0; i < count; i ++) {
            Ivar ivar = ivars[i];
            const char *name = ivar_getName(ivar);
            
            //
            NSString *key = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
            id value = [decoder decodeObjectForKey:key];
            //  設置到成員變量身上
            [self setValue:value forKey:key];
        }
        
        free(ivars);
    }
    return self;
}


7、動態的添加方法

這個我也沒用過,不過理解了消息轉發的整個流程,就能夠理解為什么這樣行得通。

// 默認方法都有兩個隱式參數,
void eat(id self,SEL sel){
    NSLog(@"%@ %@",self,NSStringFromSelector(sel));
    NSLog(@"動態添加了一個方法");

}

// 當一個對象調用未實現的方法,會調用這個方法處理,并且會把對應的方法列表傳過來.
// 剛好可以用來判斷,未實現的方法是不是我們想要動態添加的方法
+ (BOOL)resolveInstanceMethod:(SEL)sel {
    
    if (sel == NSSelectorFromString(@"eat")) {
        // 注意:這里需要強轉成IMP類型
        class_addMethod(self, sel, (IMP)eat, "v@:");
        return YES;
    }
    // 先恢復, 不然會覆蓋系統的方法
    return [super resolveInstanceMethod:sel];
}

第一次寫文章,希望對大家幫助,以后我會經常更新文章的,希望大家多多支持。

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

推薦閱讀更多精彩內容

  • 對于從事 iOS 開發人員來說,所有的人都會答出【runtime 是運行時】什么情況下用runtime?大部分人能...
    夢夜繁星閱讀 3,732評論 7 64
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,368評論 25 708
  • 李特這的這個題目不錯。寫一遍example就能看出來inorder traversal。當然啦,不能直接全部tra...
    土汪閱讀 419評論 0 0
  • 春風拂面,陽光正好。 拿了一個墊子放在陽臺上,享受著陽光的照拂,一下午的時間讀完了《文明人》一書。這本...
    請叫我木子貞閱讀 239評論 0 0
  • Buffer和Channel總是成對出現,在Java NIO中Buffer用于和NIO通道進行交互,數據總是從Ch...
    zhanglbjames閱讀 647評論 0 0