IOS处理字典设置值为nil时崩溃

2019-10-11  本文已影响0人  醉叶惜秋

经常遇到NSMutableDictionary调用[setObject: forKey:]时,若obj为nil的时候会崩溃。使用运行时替换方法,并检查是否为nil.

#import "NSMutableDictionary+Obj.h"
#import <objc/runtime.h>

@implementation NSMutableDictionary (Obj)


+ (void)load {
    Method fromMethod = class_getInstanceMethod(objc_getClass("__NSDictionaryM"), @selector(setObject:forKey:));
    Method toMethod = class_getInstanceMethod(objc_getClass("__NSDictionaryM"), @selector(em_setObject:forKey:));
    method_exchangeImplementations(fromMethod, toMethod);
}

- (void)em_setObject:(id)emObject forKey:(NSString *)key {
    if (emObject && key) {
        [self em_setObject:emObject forKey:key];
    }
}
@end
上一篇 下一篇

猜你喜欢

热点阅读