使用method-swizzling让程序更健壮
问题
熟悉iOS开发的都知道,如果我们往Array或Dictionary中插入nil,应用就会崩溃。如有下面客户端代码:
- (void)testDictionaryNullable {
id nilObj = nil;
// 1. 此处会引起崩溃
NSDictionary *dict = @{@"aa": nilObj, @"bb": @"bb"};
NSLog(@"dict: %@", dict);
NSMutableDictionary *mDict = [NSMutableDictionary new];
mDict[@"aaa"] = nilObj; // 此处不会有问题
[mDict setObject:@"bbb" forKey:@"bbb"];
// 2. 此处会引起崩溃
[mDict setObject:nilObj forKey:@"ccc"];
NSLog(@"mDict: %@", mDict);
}
- (void)testArrayNullable {
id nilObj = nil;
// 3. 此处会引起崩溃
NSArray *array = @[@"aa", nilObj];
NSLog(@"array: %@", array);
NSMutableArray *mArray = [[NSMutableArray alloc] initWithCapacity:2];
// 4. 此处会引起崩溃
mArray[0] = nilObj;
// 5. 此处会引起崩溃
[mArray addObject:nilObj];
[mArray addObject:@"bbb"];
NSLog(@"mArray: %@", mArray);
}
注: mDict[@"aaa"] = nilObj; 系统默认可以进行空值检查,不会有崩溃问题。所以以后还是推荐使用这种带下标的方式来写。
另外,解析json时,除了像mantle等json库会把空值转换为nil,系统或其他第三方库在解析json时,会把json中的null值转换为NSNull,而如果你没有好好做检查的话,把它当NSString或NSNumber来处理的话,就会出现各种unrecognized selector
异常,如:
- (void)testNSNull {
NSString *nilObj = (NSString *)[NSNull null];
NSLog(@"null:%d", [nilObj length]);
}
解决
当然,我们可以小心地使用Array、Dictionary和NSNull,对它们进行充分的检查。但是,我们为什么不能像系统对NSMutableDictionary使用下标写法时的处理一样,当插入或设置的值为nil时,我们不插入或设置,这样可以保证程序不异常,也可以大量减少对返回数据的判断。同时,让对NSNull的任何调用,都不报错,也可以减少对NSNull的检查。
我们可以使用method swizzling达到上述效果。method swizzling可以查看参考资料1。下面分别对Dictionary、Array、NSNull分别进行处理。
对Dictionary进行method swizzling
我们首先对Dictionary进行处理。先查看上面客户端代码中,第一处引起崩溃的地方,即构造NSDictionary时。我们查看console中的崩溃堆栈,如下:
我们可以在调用+[NSDictionary dictionaryWithObjects:forKyes:count]
时,对objects进行空值过滤,如果是空值的话,不插入字典。相关代码如下:
@implementation NSDictionary (Safe)
+ (void)load {
Method originalMethod = class_getClassMethod(self, @selector(dictionaryWithObjects:forKeys:count:));
Method swizzledMethod = class_getClassMethod(self, @selector(na_dictionaryWithObjects:forKeys:count:));
method_exchangeImplementations(originalMethod, swizzledMethod);
}
+ (instancetype)na_dictionaryWithObjects:(const id [])objects forKeys:(const id <NSCopying> [])keys count:(NSUInteger)cnt {
id nObjects[cnt];
id nKeys[cnt];
int i=0, j=0;
for (; i<cnt && j<cnt; i++) {
if (objects[i] && keys[i]) {
nObjects[j] = objects[i];
nKeys[j] = keys[i];
j++;
}
}
return [self na_dictionaryWithObjects:nObjects forKeys:nKeys count:j];
}
@end
经过这样处理后,客户端代码1处的代码就不会崩溃了。
我们再来看,客户端代码中的2处,对NSMutalbeDictionary调用setObject:forKey:
,同样,我们查看崩溃堆栈,如下:
注: iOS中使用了大量的
class cluster
,像NSMutaleDictionary
实例化出来的,实际上是__NSDictionaryM
类,而NSDictionary
实例化出来的,实际上是__NSPlaceholderDictionary
。class cluster
的介绍也可以查看参考资料1。
我们可以用method swizzling修改-[__NSDictionaryM setObject:forKey:]
方法,让它在设值时,先判断是否value为空,为空则不设置。代码如下:
@implementation NSMutableDictionary (Safe)
+ (void)load {
Class dictCls = NSClassFromString(@"__NSDictionaryM");
Method originalMethod = class_getInstanceMethod(dictCls, @selector(setObject:forKey:));
Method swizzledMethod = class_getInstanceMethod(dictCls, @selector(na_setObject:forKey:));
method_exchangeImplementations(originalMethod, swizzledMethod);
}
- (void)na_setObject:(id)anObject forKey:(id<NSCopying>)aKey {
if (!anObject)
return;
[self na_setObject:anObject forKey:aKey];
}
@end
对Array进行method swizzling
使用method swizzling对Array的处理,与Dictionary的处理,差不多。先打印崩溃堆栈,然后把相关函数进行method swizzling。代码如下:
@implementation NSArray (Safe)
+ (void)load {
Method originalMethod = class_getClassMethod(self, @selector(arrayWithObjects:count:));
Method swizzledMethod = class_getClassMethod(self, @selector(na_arrayWithObjects:count:));
method_exchangeImplementations(originalMethod, swizzledMethod);
}
+ (instancetype)na_arrayWithObjects:(const id [])objects count:(NSUInteger)cnt {
id nObjects[cnt];
int i=0, j=0;
for (; i<cnt && j<cnt; i++) {
if (objects[i]) {
nObjects[j] = objects[i];
j++;
}
}
return [self na_arrayWithObjects:nObjects count:j];
}
@end
@implementation NSMutableArray (Safe)
+ (void)load {
Class arrayCls = NSClassFromString(@"__NSArrayM");
Method originalMethod1 = class_getInstanceMethod(arrayCls, @selector(insertObject:atIndex:));
Method swizzledMethod1 = class_getInstanceMethod(arrayCls, @selector(na_insertObject:atIndex:));
method_exchangeImplementations(originalMethod1, swizzledMethod1);
Method originalMethod2 = class_getInstanceMethod(arrayCls, @selector(setObject:atIndex:));
Method swizzledMethod2 = class_getInstanceMethod(arrayCls, @selector(na_setObject:atIndex:));
method_exchangeImplementations(originalMethod2, swizzledMethod2);
}
- (void)na_insertObject:(id)anObject atIndex:(NSUInteger)index {
if (!anObject)
return;
[self na_insertObject:anObject atIndex:index];
}
- (void)na_setObject:(id)anObject atIndex:(NSUInteger)index {
if (!anObject)
return;
[self na_setObject:anObject atIndex:index];
}
@end
对NSNull进行处理
对NSNull的unrecognized selector
,可以运用 runtime 的知识,在forwarding时,对无法识别的selector,不抛出异常。相关知识可以参考资料2。代码如下:
@implementation NSNull (Safe)
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
NSMethodSignature *signature = [super methodSignatureForSelector:sel];
if (!signature) {
signature = [NSMethodSignature signatureWithObjCTypes:@encode(void)];
}
return signature;
}
- (void)forwardInvocation:(NSInvocation *)invocation {
}
总结
本文使用method swizzling,对Dictionary、Array进行处理,使它们在处理空值时,也不会异常而导致程序崩溃。
对NSNull,重写forwarding相关函数。使得当json解析成NSNull时,就算把它当成其他类处理,也不会抛异常而导致程序崩溃。
相关代码,已经上传github