Runtime之常見崩潰問題

一、iOS常見的崩潰類型

  • unrecognized selector sent to instance 調(diào)用了不存在的方法
  • NSArray、NSMutableArray 數(shù)組越界、插入空值等
  • NSDictionary、NSMutableDictionary 初始化有nil值、key為nil等

二、崩潰類型及解決方案

unrecognized selector sent to instance
產(chǎn)生的原因
找不到該對象的方法,系統(tǒng)發(fā)出異常

解決方案

對象調(diào)用方法經(jīng)過三個階段
1.消息發(fā)送:查詢cache和方法列表,找到了直接調(diào)用,找不到方法會進入下個階段
2.動態(tài)解析: 調(diào)用resolveInstanceMethod或resolveClassMethod方法里面可以有一次動態(tài)添加方法的機會
3.消息轉發(fā):1.首先會判斷是否有其他對象可以處理方法forwardingTargetForSelector返回一個新的對象2.如果沒有新的對象進行處理,會調(diào)用methodSignatureForSelector方法返回方法簽名,然后調(diào)用forwardInvocation

#import "NSObject+Extension.h"
#import <objc/runtime.h>

@implementation NSObject (Extension)

+(void)load{
    
    Method method1 = class_getInstanceMethod([self class], @selector(methodSignatureForSelector:));
    Method method2 = class_getInstanceMethod(self, @selector(pf_methodSignatureForSelector:));
    method_exchangeImplementations(method1, method2);
    
    Method method3 = class_getInstanceMethod([self class], @selector(forwardInvocation:));
    Method method4 = class_getInstanceMethod(self, @selector(pf_forwardInvocation:));
    method_exchangeImplementations(method3, method4);
    
}

// 返回處理對象
//-(id)forwardingTargetForSelector:(SEL)aSelector{}

-(NSMethodSignature *)pf_methodSignatureForSelector:(SEL)aSelector{
    
    // 獲取方法簽名
//    NSMethodSignature *signature = [self pf_methodSignatureForSelector:aSelector];
    
    NSMethodSignature *signature = [NSObject instanceMethodSignatureForSelector:@selector(proxyMethod)];
    return signature;
}

-(void)pf_forwardInvocation:(NSInvocation *)anInvocation{
    
    //可以做些別的什么事情
   
}

-(void)proxyMethod{
    
}

@end

NSArray、NSMutableArray 數(shù)組越界、插入空值等

NSArray相關

   NSArray *array = @[@"12",@"31"];
    // 1.1 讀取下標越界
    // 通過下標訪問元素,會調(diào)用objectAtIndexedSubscript方法
    NSString *value = array[3];//數(shù)組越界,導致崩潰
    // 1.2通過方法objectAtIndex訪問元素
    [array objectAtIndex:3]; // 數(shù)組越界、導致崩潰

解決方法

注意NSArray 是一個類簇,它真正的類型是__NSArrayI
為NSArray寫一個分類,利用runtime 替換系統(tǒng)的objectAtIndexedSubscript方法,判斷是否越界

+(void)load{
    
    Class cls = NSClassFromString(@"__NSArrayI");
    Method method1 = class_getInstanceMethod(cls, @selector(objectAtIndexedSubscript:));
    Method method2 = class_getInstanceMethod(self, @selector(pf_objectAtIndexedSubscript:));
    method_exchangeImplementations(method1, method2);

    Method method3 = class_getInstanceMethod(cls, @selector(objectAtIndex:));
    Method method4 = class_getInstanceMethod(self, @selector(pf_objectAtIndex:));
    method_exchangeImplementations(method3, method4);
}

-(id)pf_objectAtIndexedSubscript:(NSUInteger)idx{
    if (idx > self.count - 1) {
        NSAssert(NO, @"數(shù)組越界了");
        return nil;
    }else{
        return [self pf_objectAtIndexedSubscript:idx];
    }
}

-(id)pf_objectAtIndex:(NSUInteger)index{
    if (index > self.count - 1) {
        NSAssert(NO, @"數(shù)組越界了");
        return nil;
    }else{
        return [self pf_objectAtIndex:index];
    }
}

NSMutableArray相關

注意NSMutableArray 真正的類型是__NSArrayM

   NSArray *array = @[@"12",@"31"];
    // 1.1 讀取下標越界
    // 通過下標訪問元素,會調(diào)用objectAtIndexedSubscript方法
    NSString *value = array[3];//數(shù)組越界,導致崩潰
    // 1.2通過方法objectAtIndex訪問元素
    [array objectAtIndex:3]; // 數(shù)組越界、導致崩潰
    
    NSMutableArray *mArray = [NSMutableArray arrayWithArray:array];
    // 2.1 讀取下標越界
    NSString *str = mArray[3];// 數(shù)組越界、導致崩潰
    // 2.2 通過下標進行賦值
    NSString *s;
    mArray[4] = s; // 1.數(shù)組越界 2.空值導致崩潰
    // 2.3 插入數(shù)據(jù) 會調(diào)用insertObject:atIndex:
    [mArray addObject:nil]; // 插入nil值導致崩潰
    // 2.4 移除元素越界 會調(diào)用removeObjectsInRange方法
    [mArray removeObjectAtIndex:4];

解決方案

#import "NSMutableArray+Extension.h"
#import <objc/runtime.h>

@implementation NSMutableArray (Extension)

+(void)load{
    
    Class cls = NSClassFromString(@"__NSArrayM");
    // mArray[4] 會調(diào)用方法objectAtIndexedSubscript 取值
    Method method1 = class_getInstanceMethod(cls, @selector(objectAtIndexedSubscript:));
    Method method2 = class_getInstanceMethod(self, @selector(pf_objectAtIndexedSubscript:));
    method_exchangeImplementations(method1, method2);
    
    // mArray[4] 會調(diào)用setObject:atIndexedSubscript: 賦值
    Method method3 = class_getInstanceMethod(cls, @selector(setObject:atIndexedSubscript:));
    Method method4 = class_getInstanceMethod(self, @selector(pf_setObject:atIndexedSubscript:));
    method_exchangeImplementations(method3, method4);
    
//    [marray addobject] 會調(diào)用insertObject atIndex
    Method method5 = class_getInstanceMethod(cls, @selector(insertObject:atIndex:));
    Method method6 = class_getInstanceMethod(self, @selector(pf_insertObject:atIndex:));
    method_exchangeImplementations(method5, method6);
    
    Method method7 = class_getInstanceMethod(cls, @selector(removeObjectAtIndex:));
    Method method8 = class_getInstanceMethod(self, @selector(pf_removeObjectAtIndex:));
    method_exchangeImplementations(method7, method8);
    
}

// 防止數(shù)組越界導致崩潰
-(id)pf_objectAtIndexedSubscript:(NSUInteger)idx{
    if (idx > self.count - 1) {
//        NSAssert(NO, @"index %zd 越界",idx);
        return nil;
    }
    return [self pf_objectAtIndexedSubscript:idx];
}

-(void)pf_setObject:(id)obj atIndexedSubscript:(NSUInteger)idx{
    // 不能越界
    if (idx > self.count - 1) {
//        NSAssert(NO, @"index %zd 越界",idx);
        return;
    }
    // 不能插入空值
    if (obj == nil) {
//        NSAssert(NO, @"不能插入nil值");
        return;
    }
    
    [self pf_setObject:obj atIndexedSubscript:idx];
}


-(void)pf_insertObject:(id)anObject atIndex:(NSUInteger)index{
    if (!anObject) {
//        NSAssert(NO, @"不能插入nil值");
        return;
    }
    [self pf_insertObject:anObject atIndex:index];
    
}

-(void)pf_removeObjectAtIndex:(NSUInteger)index{
    if (index > self.count - 1) {
        return;
    }
    [self pf_removeObjectAtIndex:index];
}
@end

NSDictionary 相關

NSDictionary 也是一個類簇,它有多種類型

有時候,我們創(chuàng)建一個NSDictionary對象的時候,會直接使用@{}方法創(chuàng)建,而當有一個value為nil 的時候,也會導致崩潰的現(xiàn)象

NSString *str;
// 這種創(chuàng)建方式會調(diào)用__NSPlaceholderDictionary 的initWithObjects:forKeys:count:方法
    NSDictionary *dict = @{
        @"a":@"A",
        @"b":str
    };
// 如果key為nil 獲取值也會導致崩潰,調(diào)用的是__NSDictionaryI的objectForKeyedSubscript方法
NSString *value = dict[str]

解決方案 替換此方法

//__NSPlaceholderDictionary
    Class cls = NSClassFromString(@"__NSPlaceholderDictionary");
    Method method1 = class_getInstanceMethod(cls, @selector(initWithObjects:forKeys:count:));
    Method method2 = class_getInstanceMethod(self, @selector(pf_initWithObjects:forKeys:count:));
    method_exchangeImplementations(method1, method2);

//__NSDictionaryI
    Class cls2 = NSClassFromString(@"__NSDictionaryI");
    Method method3 = class_getInstanceMethod(cls2, @selector(objectForKeyedSubscript:));
    Method method4 = class_getInstanceMethod(self, @selector(pf_objectForKeyedSubscript:));
    method_exchangeImplementations(method3, method4);

// 初始化的時候,空值導致崩潰
-(instancetype)pf_initWithObjects:(id  _Nonnull const [])objects forKeys:(id<NSCopying>  _Nonnull const [])keys count:(NSUInteger)cnt{
    
    // 注意 objects 和keys 都是c語言的,所以要創(chuàng)建c語言的數(shù)組
    NSUInteger index = 0;// 數(shù)組下標,用于數(shù)據(jù)存入正確的位置
    id objectsArray[cnt]; // values
    id<NSCopying> keysArray[cnt];//keys
    
    for (int i = 0; i < cnt; i++) {
        // 如果值和key 都不為nil
        if (objects[i] != nil && keys[i] != nil) {
            objectsArray[index] = objects[i];
            keysArray[index] = keys[i];
            index++;
        }else{
            NSString *str = [NSString stringWithFormat:@"%@不能為空",keys[i]];
            NSAssert(NO, str);
        }
    }
    
    return [self pf_initWithObjects:objectsArray forKeys:keysArray count:index];
}

-(id)pf_objectForKeyedSubscript:(id)key{
    if (!key) {
        NSAssert(NO, @"key 不能為空");
        return nil;
    }
    
    id obj = [self pf_objectForKeyedSubscript:key];
    
    if ([obj isKindOfClass:[NSNull class]]) {
        return nil;
    }
    
    return [self pf_objectForKeyedSubscript:key];
}

NSMutableDictionary相關

NSMutableDictionary 一般是__NSDictionaryM

 /// 通過類名字符串創(chuàng)建類
    Class cls = NSClassFromString(@"__NSDictionaryM");
    Method method1 = class_getInstanceMethod(cls, @selector(setObject:forKeyedSubscript:));
    Method method2 = class_getInstanceMethod(self, @selector(pf_setObject:forKeyedSubscript:));
    
    method_exchangeImplementations(method1, method2);
    
    Method method3 = class_getInstanceMethod(cls, @selector(setValue:forKey:));
    Method method4 = class_getInstanceMethod(self, @selector(pf_setObject:forKey:));
    method_exchangeImplementations(method3, method4);
    
    Method method5 = class_getInstanceMethod(cls, @selector(objectForKeyedSubscript:));
    Method method6 = class_getInstanceMethod(self, @selector(pf_objectForKeyedSubscript:));
    method_exchangeImplementations(method5, method6);

-(void)pf_setObject:(id)obj forKeyedSubscript:(id<NSCopying>)key{
    if (!key) return;// 如果key為nil 會導致崩潰
    [self pf_setObject:obj forKeyedSubscript:key];
}

//攔截系統(tǒng)的setObject forKey方法
-(void)pf_setObject:(id)anObject forKey:(id<NSCopying>)aKey{
    // 1.當key為nil 的時候,set方法會崩潰
    if (!aKey) return;
    [self pf_setObject:anObject forKey:aKey];
}

-(id)pf_objectForKeyedSubscript:(id)key{
    if (!key) {
        return nil;
    }
    
    id obj = [self pf_objectForKeyedSubscript:key];
    
    if ([obj isKindOfClass:[NSNull class]]) {
        return nil;
    }
    
    return [self pf_objectForKeyedSubscript:key];
}
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

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