NSDictionary+NilSafe.h 小神器
后台各种传,垃圾参数,各种空值,各种取空字典中的值,之前用空值来判断,但是太麻烦,而且不晓得具体是哪一个,所以后来找到一个神器。虽然有点暴力,但是能解决很打一部分的crash问题。
.h文件
@interface NSDictionary (NilSafe)
@end
@interface NSMutableDictionary (NilSafe)
@end
.m文件
#import <objc/runtime.h>
#import "NSDictionary+NilSafe.h"
@implementation NSObject (Swizzling)
+ (BOOL)gl_swizzleMethod:(SEL)origSelwithMethod:(SEL)altSel {
MethodorigMethod =class_getInstanceMethod(self, origSel);
MethodaltMethod =class_getInstanceMethod(self, altSel);
if(!origMethod || !altMethod) {
returnNO;
}
class_addMethod(self,
origSel,
class_getMethodImplementation(self, origSel),
method_getTypeEncoding(origMethod));
class_addMethod(self,
altSel,
class_getMethodImplementation(self, altSel),
method_getTypeEncoding(altMethod));
method_exchangeImplementations(class_getInstanceMethod(self, origSel),
class_getInstanceMethod(self, altSel));
return YES;
}
+ (BOOL)gl_swizzleClassMethod:(SEL)origSel withMethod:(SEL)altSel {
return[object_getClass((id)self)gl_swizzleMethod:origSelwithMethod:altSel];
}
@end
@implementation NSDictionary (NilSafe)
+ (void)load{
staticdispatch_once_tonceToken;
dispatch_once(&onceToken, ^{
[selfgl_swizzleMethod:@selector(initWithObjects:forKeys:count:)withMethod:@selector(gl_initWithObjects:forKeys:count:)];
[selfgl_swizzleClassMethod:@selector(dictionaryWithObjects:forKeys:count:)withMethod:@selector(gl_dictionaryWithObjects:forKeys:count:)];
});
}
+ (instancetype)gl_dictionaryWithObjects:(constid[])objectsforKeys:(constid [])keyscount:(NSUInteger)cnt {
idsafeObjects[cnt];
idsafeKeys[cnt];
NSUIntegerj =0;
for(NSUIntegeri =0; i < cnt; i++) {
idkey = keys[i];
idobj = objects[i];
if(!key || !obj) {
continue;
}
safeKeys[j] = key;
safeObjects[j] = obj;
j++;
}
return [self gl_dictionaryWithObjects:safeObjects forKeys:safeKeys count:j];
}
- (instancetype)gl_initWithObjects:(constid[])objectsforKeys:(constid [])keyscount:(NSUInteger)cnt {
idsafeObjects[cnt];
idsafeKeys[cnt];
NSUIntegerj =0;
for(NSUIntegeri =0; i < cnt; i++) {
idkey = keys[i];
idobj = objects[i];
if(!key || !obj) {
continue;
}
if(!obj) {
obj = [NSNullnull];
}
safeKeys[j] = key;
safeObjects[j] = obj;
j++;
}
return[selfgl_initWithObjects:safeObjectsforKeys:safeKeyscount:j];
}
@end
@implementation NSMutableDictionary (NilSafe)
+ (void)load{
staticdispatch_once_tonceToken;
dispatch_once(&onceToken, ^{
Classclass =NSClassFromString(@"__NSDictionaryM");
[classgl_swizzleMethod:@selector(setObject:forKey:)withMethod:@selector(gl_setObject:forKey:)];
[classgl_swizzleMethod:@selector(setObject:forKeyedSubscript:)withMethod:@selector(gl_setObject:forKeyedSubscript:)];
});
}
- (void)gl_setObject:(id)anObjectforKey:(id)aKey {
if(!aKey || !anObject) {
return;
}
[selfgl_setObject:anObjectforKey:aKey];
}
- (void)gl_setObject:(id)obj forKeyedSubscript:(id<NSCopying>)key {
if(!key || !obj) {
return;
}
[self gl_setObject:obj forKeyedSubscript:key];
}
@end