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: