美文网首页iOS OC
解决IOS字典设置值为nil时崩溃

解决IOS字典设置值为nil时崩溃

作者: I_YoYo | 来源:发表于2018-04-22 11:20 被阅读525次

    经常遇到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
    

    相关文章

      网友评论

        本文标题:解决IOS字典设置值为nil时崩溃

        本文链接:https://www.haomeiwen.com/subject/odwqlftx.html