#import "NSMutableDictionary+NullSaf.h"
#import<objc/runtime.h>
@implementation NSMutableDictionary (NullSaf)
- (void)swizzeMethod:(SEL)origSelector withMethod:(SEL)newSelector
{
Class class = [self class];
Method originalMethod = class_getInstanceMethod(class, origSelector);//Method是運行時庫的類
Method swizzledMethod = class_getInstanceMethod(class, newSelector);
BOOL didAddMethod = class_addMethod(class, origSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class, newSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
}else{
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
- (void)safe_setObject:(id)value forKey:(NSString* )key{
if (value) {
[self safe_setObject:value forKey:key];
}else{
NSLog(@"[NSMutableDictionary setObject: forKey:%@]值不能為空;",key);
}
}
- (void)safe_removeObjectForKey:(NSString *)key{
if ([self objectForKey:key]) {
[self safe_removeObjectForKey:key];
}else{
NSLog(@"[NSMutableDictionary setObject: forKey:%@]值不能為空;",key);
}
}
+ (void)load{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
id obj = [[self alloc]init];
[obj swizzeMethod:@selector(setObject:forKey:) withMethod:@selector(safe_setObject:forKey:)];
[obj swizzeMethod:@selector(removeObjectForKey:) withMethod:@selector(safe_removeObjectForKey:)];
});
}
@end
--------------------------------------------------
這樣當(dāng)項目中出現(xiàn)這樣的代碼:
id obj = nil;
NSMutableDictionary *m_dict = [NSMutableDictionary dictionary];
[dict setObject:obj forKey:@"666"];時程序就不會崩潰了尺碰。
總結(jié):此方法主要是解決字典傳空值、removeObjectForKey的崩潰,利用運行時替換原來的方法牌捷,避免程序出現(xiàn)崩潰。