您的位置:首页 > 其它

NSMutableDictionary添加数据时遇到的问题

2015-03-19 13:53 344 查看
//根据需求,我需要在网络请求后在数据源里面添加另外的一个参数
[manager GET:@"http://mobile.pinlehuo.com/api.php?m=Wallet&a=bindcard&user_id=1101" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
for (NSMutableDictionary *dic in responseObject[@"data"]) {
[dic setValue:@"YES" forKey:@"checked"];
[dataArray addObject:dic];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@", error);
}];
//我按照上面的方法直接在遍历后往字典里面添加参数 会报这个错误
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'在网上查了一下,说是因为2个字典的内存地址不一样照成的

//下面我又初始化了一个字典,根据现有的字典创建字典 成功了
NSMutableDictionary *mutableItem;
for (NSDictionary *dic in responseObject[@"data"]) {
// NSLog(@"%@", dic);
mutableItem = [NSMutableDictionary dictionaryWithDictionary:dic];
[mutableItem setValue:@"YES" forKey:@"checked"];

[dataArray addObject:mutableItem];
}

//下面附上一些NSDictionary内容
来自http://blog.csdn.net/ms2146/article/details/8656787
//创建字典
NSDictionary *dic1 = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
NSLog(@"dic1 :%@", dic1);

//创建多个字典
NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:
@"value1", @"key1",
@"value2", @"key2",
@"value3", @"key3",
@"value4", @"key4",
nil];
NSLog(@"dic2 :%@", dic2);

//根据现有的字典创建字典
NSDictionary *dic3 = [NSDictionary dictionaryWithDictionary:dic2];
NSLog(@"dic3 :%@", dic3);

//根据key获取value
NSLog(@"key3 value :%@", [dic3 objectForKey:@"key3"]);

//获取字典数量
NSLog(@"dic count :%d", dic3.count);

//所有的键集合
NSArray *keys = [dic3 allKeys];
NSLog(@"keys :%@", keys);

//所有值集合
NSArray *values = [dic3 allValues];
NSLog(@"values :%@", values);

NSMutableDictionary *mutableDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
@"mvalue1", @"mkey1",
@"mvalue2", @"mkey2", nil];
//添加现有的字典数据
[mutableDic addEntriesFromDictionary:dic3];
NSLog(@"mutableDic :%@",mutableDic);

//添加新的键值对象
[mutableDic setValue:@"set1" forKey:@"setKey1"];
NSLog(@"set value for key :%@",mutableDic);

//以新的字典数据覆盖旧的字典数据
[mutableDic setDictionary:dic2];
NSLog(@" set dictionary :%@",mutableDic);

//根据key删除value
[mutableDic removeObjectForKey:@"key1"];
NSLog(@"removeForkey :%@",mutableDic);

//快速遍历
for(id key in mutableDic) {
NSLog(@"key :%@  value :%@", key, [mutableDic objectForKey:key]);
}

//枚举遍历
NSEnumerator *enumerator = [mutableDic keyEnumerator];
id key = [enumerator nextObject];
while (key) {
NSLog(@"enumerator :%@", [mutableDic objectForKey:key]);
key = [enumerator nextObject];
}

//根据key数组删除元素
[mutableDic removeObjectsForKeys:keys];
NSLog(@"removeObjectsForKeys :%@",mutableDic);

//删除所有元素
[mutableDic removeAllObjects];

NSLog(@"remove all :%@", mutableDic);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: