NSDictionary創(chuàng)建有兩種方法,
1.NSDictionary *dic =@{@"xxx":@"xxx”};
2.NSDictionary *dic =[NSDictionary dictionaryWithObjectsAndKeys:string01,@"xxx",string02,@“xxx”,string03,@"xxx",nil];
區(qū)別在于:
但是用第一種創(chuàng)建的dic里面的元素一定不能為空,否則就會(huì)崩潰。
但是第二種也有缺陷 當(dāng)string01 為空的時(shí)候 string02 后面的也會(huì)變null
解決方案:
當(dāng)object有可能為nil的時(shí)候,采用setObject:forKey:
NSString* string1 = nil;
NSString* string2 = @"string2";
NSMutableDictionary* dic = [NSMutableDictionary dictionary];
if (string1) {
[dic setObject:string1 forKey:@"string1"];
}
if (string2) {
[dic setObject:string2 forKey:@"string2"];
}
[dic setObject:@"string3" forKey:@"string3"];
當(dāng)然還有更便捷的方法,使用setValue:forKey:
NSString* string1 = nil;
NSString* string2 = @"string2";
NSMutableDictionary* dic = [NSMutableDictionary dictionary];
[dic setValue:string1 forKey:@"string1"];
[dic setValue:string2 forKey:@"string2"];
[dic setValue:@"string3" forKey:@"string3"];
請(qǐng)注意,setValue:forKey:與setObject:forKey:不完全等同,最大的區(qū)別有兩點(diǎn):
- setValue:forKey:只接受NSString*類型的key
- setValue:forKey:當(dāng)value為nil時(shí),將調(diào)用removeObjectForKey: