NSDictionary創建有兩種方法,
1.NSDictionary *dic =@{@"xxx":@"xxx”};
2.NSDictionary *dic =[NSDictionary dictionaryWithObjectsAndKeys:string01,@"xxx",string02,@“xxx”,string03,@"xxx",nil];
區別在于:
但是用第一種創建的dic里面的元素一定不能為空,否則就會崩潰。
但是第二種也有缺陷 當string01 為空的時候 string02 后面的也會變null
解決方案:
當object有可能為nil的時候,采用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"];
當然還有更便捷的方法,使用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"];
請注意,setValue:forKey:與setObject:forKey:不完全等同,最大的區別有兩點:
- setValue:forKey:只接受NSString*類型的key
- setValue:forKey:當value為nil時,將調用removeObjectForKey: