iOS中我們經(jīng)常會(huì)對(duì)
Dictionary
進(jìn)行初始化操作介返,有時(shí)我們對(duì)一些傳參的key
或者Value
在Dictionary
進(jìn)行初始化時(shí)焕妙,會(huì)忘記進(jìn)行判斷蒋伦!然后當(dāng)為空時(shí)奔潰發(fā)生了!我們先看兩個(gè)簡(jiǎn)單的初始化代碼:
//key 為空
NSString *t = nil;
NSDictionary *dic = @{t:@"Test"};
// value 為空
NSString *t = nil;
NSDictionary *dic = @{@"Test":t};
//運(yùn)行奔潰報(bào)告
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]'
看到這焚鹊,你還會(huì)對(duì)那些感覺(jué)一定不會(huì)為空的代碼自信滿滿么痕届!如果多寫一行判斷或者多寫一行
NSAssert
呢!
NSString *t = nil;
if (!t) {
//do something末患!
}
NSAssert(t != nil, @"Initial dictionary key or value can't is nil");
NSDictionary *dic = @{@"111":t};