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 不承认它是可变子类的方法(因为它不能改变它的内容)。