iOS -------字典傳空值、removeObjectForKey的崩潰避免的實現

#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


--------------------------------------------------

這樣當項目中出現這樣的代碼:

id obj = nil;

NSMutableDictionary *m_dict = [NSMutableDictionary dictionary];

[dict setObject:obj forKey:@"666"];時程序就不會崩潰了。

總結:此方法主要是解決字典傳空值、removeObjectForKey的崩潰,利用運行時替換原來的方法,避免程序出現崩潰。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容