当前位置: 代码迷 >> Iphone >> 如何根据key修改NSMutableArray中的值。
  详细解决方案

如何根据key修改NSMutableArray中的值。

热度:61   发布时间:2016-04-25 06:08:52.0
怎么根据key修改NSMutableArray中的值。。。。
[array objectAtIndex:row]
修改上面中key为“aa”的值
NSMutableDictionary *item = [[NSMutableDictionary alloc]init];
item=[array objectAtIndex:row];
[item setObject:@“222” forKey:@"aa"];
报错:[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'

球各位前辈解惑下  谢谢。。
------解决方案--------------------
因为array里那个dictionary是不可变的,用一个可变字典写回去

------解决方案--------------------
NSMutableDictionary *item = [[NSMutableDictionary alloc]init];
item=[array objectAtIndex:row];
[item setObject:@“222” forKey:@"aa"];

这个。。。你写法有问题。。。

首先第一句,生成一个 可变 字典(假设地址为 0x000001)
第二句,你副了一个 地址 给 item,那么 你刚生成得000001会找不到。。。
NSObject  *obj =  [array objectAtIndex: row]   (假设地址 000002)
item 地址 为 000002.  000001地址你旧访问不到了,变成了一个 实际存在而又访问不到得地址(内存泄漏,有arc 例外)

你应当: item  addEntributeFrom :(NSDictionary *)dic  
000001地址得字典  添加 000002字典里面得属性。。。。

就像可变数组那样。。。
------解决方案--------------------
NSDictionary *item =[array objectAtIndex:row];
NSMutableDictionary *mutableItem = [NSMutableDictionary dictionaryWithDictionary:item];
[mutableItem setObject:@“222” forKey:@"aa"];
[array setObject: mutableItem atIndexedSubscript:row]