利用runtime运行时解决IOS字典设置值为nil时崩溃

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

#import "NSMutableDictionary+Obj.h"
#import 

@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

你可能感兴趣的:(利用runtime运行时解决IOS字典设置值为nil时崩溃)