0
    NSMutableArray *tmpMutArr = [NSMutableArray arrayWithArray:allObjectsArray];
    NSLog(@"The content of array is%@",tmpMutArr);

    int index;

     for (int i=0;i<[tmpMutArr count];i++) 
     {
     if([[tmpMutArr  objectAtIndex:i] isKindOfClass:[NSDictionary class]])
     {
     NSMutableDictionary *tempDict = [tmpMutArr  objectAtIndex:i];
         if([[tempDict valueForKey:@"Name"] isEqualToString:[NSString stringWithFormat:@"%@", nameString]])
     {
     index = i;

     }
     }
     }

     [tmpMutArr replaceObjectAtIndex:index withObject:[NSDictionary dictionaryWithDictionary:mutDict]];

这段代码并没有按照我的意愿替换tmpMutArr 中的匹配对象,而是替换了 tmpMutArr 中的所有对象。如何只替换我想要的索引?

我知道 tmpMutArr 包含替换之前的所有对象,所以我只需要正确指定我认为的索引。怎么做?

4

2 回答 2

5
NSMutableArray *tmpMutArr = [NSMutableArray arrayWithArray:allObjectsArray];
NSLog(@"The content of array is%@",tmpMutArr);

int index;

for (int i=0;i<[tmpMutArr count];i++) 
{
    if([[tmpMutArr  objectAtIndex:i] isKindOfClass:[NSDictionary class]])
    {
        NSMutableDictionary *tempDict = [tmpMutArr  objectAtIndex:i];
        if([[tempDict valueForKey:@"Name"] isEqualToString:nameString])
        {
            index = i;
            break; // << added break
        }
    }
}

[tmpMutArr replaceObjectAtIndex:index withObject:[NSDictionary dictionaryWithDictionary:mutDict]];
于 2012-08-14T18:19:31.020 回答
0

也许,你应该尝试这个版本......你没有指定需要哪个索引,我想是第一个。

for (int i=0;i<[tmpMutArr count];i++) {
     if([[tmpMutArr  objectAtIndex:i] isKindOfClass:[NSDictionary class]]) {
         NSMutableDictionary *tempDict = [tmpMutArr  objectAtIndex:i];
         if([[tempDict valueForKey:@"Name"] isEqualToString:[NSString stringWithFormat:@"%@", nameString]]) {
             index = i;
             break; // when you find the first one, you should go out from the iteration
         }
     }
 }
于 2012-08-14T18:31:36.400 回答