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