您的位置:首页 > 移动开发 > Objective-C

iOS字典 setValue 和 setObject的区别

2016-10-24 20:38 274 查看
实例说明

NSString name = @"张三";
NSString name1 = nil;

NSMutableDictionary *paramters = [[NSMutableDictionary alloc] init];
[paramters setObject:name forKey:@"userName"]; // 不会奔溃

NSMutableDictionary *paramters1 = [[NSMutableDictionary alloc] init];
[paramters setObject:name1 forKey:@"userName"]; // 奔溃

setObejct的value不能为nil

所以在项目中  传参数的时候 有时候会因为值为nil而奔溃,相信都有遇到过吧。 如果使用setObject 一定要保证value不能为nil

如果要value为nil 但又不会让其奔溃怎么办,那就要使用setValue
NSMutableDictionary *paramters2 = [[NSMutableDictionary alloc] init];
[paramters setValue:name forKey:@"userName"]; // 不会奔溃

NSMutableDictionary *paramters3 = [[NSMutableDictionary alloc] init];
[paramters setValue:name1 forKey:@"userName"]; // 不会奔溃
如果使用setValue 当value为nil的时候 会自己调用 下面这个方法
- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{

}

小小知识点,但在项目中随处可见,不建议说哪个好!但自己····因为也是我在项目中遇到的坑··
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: