2012-08-14 112 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 
     } 
    } 
}