网上关于setValue和setObject的区别的文章很多,说的并不准确,首先我们得知道:setObject:ForKey: 是NSMutableDictionary特有的;setValue:ForKey:是KVC的主要方法
话不多说,上代码:
- (void)viewDidLoad { [super viewDidLoad]; //setObject和setvalue的区别 NSMutableDictionary *dic = [NSMutableDictionary dictionary]; NSMutableArray *array = [NSMutableArray array]; [array insertObject:@"1" atIndex:0]; [array insertObject:@"2" atIndex:1]; [dic setObject:[NSNull null] forKey:@"haha"]; [dic setObject:[NSNull null] forKey:array]; [dic setObject:[NSNull null] forKey:[NSNull null]]; [dic setObject:@1 forKey:@""]; [dic setObject:@"" forKey:@1]; [dic setObject:nil forKey:@""]; [dic setObject:@"" forKey:nil]; NSLog(@"dic:%@",dic); //setobject中的key和value可以为除了nil外的任何对象 NSLog(@"*****************"); [dic removeAllObjects]; NSLog(@"dic:%@",dic); [dic setValue:[NSNull null] forKey:@"haha"]; [dic setValue:[NSNull null] forKey:array]; [dic setValue:[NSNull null] forKey:[NSNull null]]; [dic setValue:@1 forKey:@""]; [dic setValue:@"" forKey:@1]; [dic setValue:nil forKey:@""]; [dic setValue:@"" forKey:nil]; [dic setValue:@"" forKey:@"hehe"]; [dic setValue:array forKey:@""]; NSLog(@"dic2:%@",dic); //setValue中的KEY只能为字符串 value可以为nil也可以为空对象[NSNull null] }程序崩溃,原因就在这几个警告,由代码得出以下结论:
setobject中的key和value可以为除了nil外的任何对象
setValue中的key只能为字符串 value可以为nil也可以为空对象[NSNull null]以及全部对象
新闻热点
疑难解答