Get the correct index of dictionary

让人想犯罪 __ 提交于 2019-12-25 04:55:16

问题


    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]];

This code is not replacing the matching object in tmpMutArr as I want it to, but replaces all objects in tmpMutArr instead. How to replace only the index I want?

I know that tmpMutArr containing all objects before the replacement, so I just need to specify the index correctly I think. How to do so?


回答1:


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]];



回答2:


maybe, you should try to this version... you have not specified which index is needed, I suppose the first one.

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
         }
     }
 }


来源:https://stackoverflow.com/questions/11958338/get-the-correct-index-of-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!