iOS Runtime的實(shí)際應(yīng)用

iOS Runtime的實(shí)際應(yīng)用

導(dǎo)入

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

Runtime的實(shí)際應(yīng)用

1、動(dòng)態(tài)給分類添加屬性

這個(gè)應(yīng)該使用的比較頻繁,通過runtime動(dòng)態(tài)添加屬性,可以給系統(tǒng)類添加自定義屬性,靈活使用,可以帶來神奇的效果。

//(block直接調(diào)用手勢(shì)的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

這個(gè)方法,一般在特殊的情況下使用,可以將系統(tǒng)的方法轉(zhuǎn)換成自定義的方法,在一些特殊的場(chǎng)景,比如iOS的平板開發(fā)及手機(jī)開發(fā)代碼整合時(shí),使用起來比較方便。

@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、字典轉(zhuǎn)模型

這個(gè)很常見,網(wǎng)上所有的字典轉(zhuǎn)模型的三方框架最底層的實(shí)現(xiàn)原理莫過于此,你們?nèi)タ匆幌戮蜁?huì)明白了,比如MJExtension。

const char *kPropertyListKey = "YFPropertyListKey";
+ (NSArray *)yf_objcProperties
{
    /* 獲取關(guān)聯(lián)對(duì)象 */
    NSArray *ptyList = objc_getAssociatedObject(self, kPropertyListKey);
    /* 如果 ptyList 有值,直接返回 */
    if (ptyList) {
        return ptyList;
    }
    /* 調(diào)用運(yùn)行時(shí)方法, 取得類的屬性列表 */
    /* 成員變量:
     * 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)
     * 協(xié)議:
     * class_copyProtocolList(__unsafe_unretained Class cls, unsigned int *outCount)
     */
    unsigned int outCount = 0;
    /**
     * 參數(shù)1: 要獲取得類
     * 參數(shù)2: 類屬性的個(gè)數(shù)指針
     * 返回值: 所有屬性的數(shù)組, C 語言中,數(shù)組的名字,就是指向第一個(gè)元素的地址
     */
    /* 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++) {
        /* 從數(shù)組中取得屬性 */
        objc_property_t property = propertyList[i];
        /* 從 property 中獲得屬性名稱 */
        const char *propertyName_C = property_getName(property);
        /* 將 C 字符串轉(zhuǎn)化成 OC 字符串 */
        NSString *propertyName_OC = [NSString stringWithCString:propertyName_C encoding:NSUTF8StringEncoding];
        [mtArray addObject:propertyName_OC];
    }
    /* 設(shè)置關(guān)聯(lián)對(duì)象 */
    /**
     *  參數(shù)1 : 對(duì)象self
     *  參數(shù)2 : 動(dòng)態(tài)添加屬性的 key
     *  參數(shù)3 : 動(dòng)態(tài)添加屬性值
     *  參數(shù)4 : 對(duì)象的引用關(guān)系
     */
    objc_setAssociatedObject(self, kPropertyListKey, mtArray.copy, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    /* 釋放 */
    free(propertyList);
    return mtArray.copy;
}
+ (instancetype)modelWithDict:(NSDictionary *)dict {
    /* 實(shí)例化對(duì)象 */
    id objc = [[self alloc]init];
    /* 使用字典,設(shè)置對(duì)象信息 */
    /* 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 設(shè)置數(shù)值 */
            [objc setValue:obj forKey:key];
        }
    }];
    /* 返回對(duì)象 */
    return objc;
}

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

這個(gè)在判斷是否子類重寫了父類的方法時(shí)會(huì)用到。

#pragma mark - 獲取所有的屬性(包括私有的)
- (void)getAllIvar {
    unsigned int count = 0;
    //Ivar:定義對(duì)象的實(shí)例變量,包括類型和名字。
    //獲取所有的屬性(包括私有的)
    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、對(duì)私有屬性修改

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

#pragma mark - 對(duì)私有變量的更改
- (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);
    }
    //對(duì)私有變量的更改
    Ivar m_address = members[1];
    object_setIvar(onePerson, m_address, @"上海");
    NSLog(@"對(duì)私有變量的(地址)進(jìn)行更改 : %@",[onePerson description]);
    
}

6、歸檔:解檔

快速定義歸檔和解檔屬性

@implementation MMModel

- (void)encodeWithCoder:(NSCoder *)encoder {
    unsigned int count = 0;
    //  利用runtime獲取實(shí)例變量的列表
    Ivar *ivars = class_copyIvarList([self class], &count);
    for (int i = 0; i < count; i ++) {
        //  取出i位置對(duì)應(yīng)的實(shí)例變量
        Ivar ivar = ivars[i];
        //  查看實(shí)例變量的名字
        const char *name = ivar_getName(ivar);
        //  C語言字符串轉(zhuǎn)化為NSString
        NSString *nameStr = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
        //  利用KVC取出屬性對(duì)應(yīng)的值
        id value = [self valueForKey:nameStr];
        //  歸檔
        [encoder encodeObject:value forKey:nameStr];
    }
    
    //  記住C語言中copy出來的要進(jìn)行釋放
    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];
            //  設(shè)置到成員變量身上
            [self setValue:value forKey:key];
        }
        
        free(ivars);
    }
    return self;
}


7、動(dòng)態(tài)的添加方法

這個(gè)我也沒用過,不過理解了消息轉(zhuǎn)發(fā)的整個(gè)流程,就能夠理解為什么這樣行得通。

// 默認(rèn)方法都有兩個(gè)隱式參數(shù),
void eat(id self,SEL sel){
    NSLog(@"%@ %@",self,NSStringFromSelector(sel));
    NSLog(@"動(dòng)態(tài)添加了一個(gè)方法");

}

// 當(dāng)一個(gè)對(duì)象調(diào)用未實(shí)現(xiàn)的方法,會(huì)調(diào)用這個(gè)方法處理,并且會(huì)把對(duì)應(yīng)的方法列表傳過來.
// 剛好可以用來判斷,未實(shí)現(xiàn)的方法是不是我們想要?jiǎng)討B(tài)添加的方法
+ (BOOL)resolveInstanceMethod:(SEL)sel {
    
    if (sel == NSSelectorFromString(@"eat")) {
        // 注意:這里需要強(qiáng)轉(zhuǎn)成IMP類型
        class_addMethod(self, sel, (IMP)eat, "v@:");
        return YES;
    }
    // 先恢復(fù), 不然會(huì)覆蓋系統(tǒng)的方法
    return [super resolveInstanceMethod:sel];
}

第一次寫文章,希望對(duì)大家?guī)椭?,以后我?huì)經(jīng)常更新文章的,希望大家多多支持。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 對(duì)于從事 iOS 開發(fā)人員來說,所有的人都會(huì)答出【runtime 是運(yùn)行時(shí)】什么情況下用runtime?大部分人能...
    夢(mèng)夜繁星閱讀 3,812評(píng)論 7 64
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,219評(píng)論 25 708
  • 李特這的這個(gè)題目不錯(cuò)。寫一遍example就能看出來inorder traversal。當(dāng)然啦,不能直接全部tra...
    土汪閱讀 479評(píng)論 0 0
  • 春風(fēng)拂面,陽光正好。 拿了一個(gè)墊子放在陽臺(tái)上,享受著陽光的照拂,一下午的時(shí)間讀完了《文明人》一書。這本...
    請(qǐng)叫我木子貞閱讀 278評(píng)論 0 0
  • Buffer和Channel總是成對(duì)出現(xiàn),在Java NIO中Buffer用于和NIO通道進(jìn)行交互,數(shù)據(jù)總是從Ch...
    zhanglbjames閱讀 1,052評(píng)論 0 0

友情鏈接更多精彩內(nèi)容