获取正确的字典索引

时间:2012-08-14 18:16:38

标签: objective-c indexing nsmutablearray

    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在替换之前包含所有对象,所以我只需要正确指定索引。怎么做?

2 个答案:

答案 0 :(得分: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]];

答案 1 :(得分: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
         }
     }
 }