我有NSMutableArray数据如下。
(
{
Id = 3;
Name = Fahim;
},
{
Id = 2;
Name = milad;
},
{
Id = 1;
Name = Test;
}
)
现在我想将名称从Test更新为Omar(id = 1)。
知道如何完成这项工作吗?
通过以下答案,我收到的错误为-[__NSDictionaryI setObject:forKey:]: unrecognized selector sent to instance
。要解决该问题,我已将[feeds addObject:[item copy]]
更改为[feeds addObject:item]
答案 0 :(得分:-1)
for (NSMutableDictionary* aDict in yourMutableArray) {
if (aDict[@"id"] == 1) {
[aDict setObject:@"Omar" forKey:@"Name"];
}
}
编辑:
NSMutableArray* mutableArray = [[NSMutableArray alloc]init];
NSDictionary* item1Dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"1",@"id",
@"Fahim",@"name"
, nil];
NSMutableDictionary* item1 = [NSMutableDictionary dictionaryWithDictionary:item1Dict];
[mutableArray addObject:item1];
NSDictionary* item2Dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"2",@"id",
@"milad",@"name"
, nil];
NSMutableDictionary* item2 = [NSMutableDictionary dictionaryWithDictionary:item2Dict];
[mutableArray addObject:item2];
NSDictionary* item3Dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"3",@"id",
@"test",@"name"
, nil];
NSMutableDictionary* item3 = [NSMutableDictionary dictionaryWithDictionary:item3Dict];
[mutableArray addObject:item3];
NSLog(@"%@",mutableArray);
for (NSMutableDictionary* aDict in mutableArray) {
if ([aDict[@"id"] isEqualToString:@"3"]) {
[aDict setObject:@"Omar" forKey:@"name"];
}
}
NSLog(@"%@",mutableArray);
非常优雅:
NSMutableArray* mutableArray = [[NSMutableArray alloc]init];
NSArray* name = [NSArray arrayWithObjects:@"Fahin",@"milad",@"test", nil];
for (int i = 0; i < name.count; i++) {
NSDictionary* itemd = [NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"%i",i],@"id",
name[i],@"name"
, nil];
NSMutableDictionary* item = [NSMutableDictionary dictionaryWithDictionary:itemd];
//or
//NSMutableDictionary* item = [item mutableCopy];
[mutableArray addObject:item];
}
NSLog(@"%@",mutableArray);
for (NSMutableDictionary* aDict in mutableArray) {
if ([aDict[@"id"] isEqualToString:@"2"]) {
[aDict setObject:@"Omar" forKey:@"name"];
}
}
NSLog(@"%@",mutableArray);
日志是:
2013-10-18 00:51:48.845 test[34919:60b] (
{
id = 1;
name = Fahim;
},
{
id = 2;
name = milad;
},
{
id = 3;
name = test;
}
)
第二次登录:
2013-10-18 00:52:06.887 test[34919:60b] (
{
id = 1;
name = Fahim;
},
{
id = 2;
name = milad;
},
{
id = 3;
name = Omar;
}
)
EDIT2副本:
-copy,由可变的Cocoa类实现,总是返回它们的不可变对应物。当NSMutableDictionary被发送-copy时,它返回一个包含相同对象的NSDictionary。 NSMutableDictionary是NSDictionary的子类,编译器不会抱怨。 NSDictionary不承认它是可变子类的方法(因为它不能改变它的内容)。