2012-08-14 68 views
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,所以我只需要指定正确,我认为指数。如何做?

+0

你的意图确实是未知的。请在你的询问 – tGilani 2012-08-14 18:22:00

+0

答固定我的问题更全面。 – ingenspor 2012-08-14 18:22:33

回答

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

说的NSString stringWithFormat已经在OP的岗位是多余的... – 2012-08-14 18:24:00

+0

是的,我只是复制粘贴格式OP的源代码。感谢您注意,@ H2CO3。 – Dmitriy 2012-08-14 18:38:31

+0

欢迎您(即发生在我身上还有,我只是在代码冗余,因为它浪费处理器时间过于敏感;) – 2012-08-14 18:39:35

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