iOS中我们经常会对
Dictionary
进行初始化操作,有时我们对一些传参的key
或者Value
在Dictionary
进行初始化时,会忘记进行判断!然后当为空时奔溃发生了!我们先看两个简单的初始化代码:
//key 为空
NSString *t = nil;
NSDictionary *dic = @{t:@"Test"};
// value 为空
NSString *t = nil;
NSDictionary *dic = @{@"Test":t};
//运行奔溃报告
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]'
看到这,你还会对那些感觉一定不会为空的代码自信满满么!如果多写一行判断或者多写一行
NSAssert
呢!
NSString *t = nil;
if (!t) {
//do something!
}
NSAssert(t != nil, @"Initial dictionary key or value can't is nil");
NSDictionary *dic = @{@"111":t};