2012-02-09 202 views
0

我想要做的是搜索特定目標字典的字典數組,如果找到,用目標字典替換原始數組中的實際字典。搜索算法有效,但字典的複製不會。有問題的主線是一個說:通過指針複製NSMutableDictionary

tempDict=targetDict;

我希望tempDict將是一個指向原始詞典原始數組,但嘗試登錄的作者名字的時候,我得到「 moe「而不是」steve「。

-(void)viewDidAppear 
{ 
    [actualDictionary setObject:@"test" forKey:@"mainNote"]; 
    [actualDictionary setObject:@"moe" forKey:@"authorName"]; 

    [targetDictionary setObject:@"test" forKey:@"mainNote"]; 
    [targetDictionary setObject:@"steve" forKey:@"authorName"]; 

    [arrayOfNotes addObject:actualDictionary]; 
    [self beginSearchWithMainArray]; 
} 

-(void)beginSearchWithMainArray; 
{ 
    [self searchArray:arrayOfNotes forDict:targetDictionary]; 
} 
-(void)searchArray:(NSMutableArray*)array forDict:(NSMutableDictionary*)targetDict 
{ 
    NSString *targetText=[targetDict objectForKey:@"mainNote"]; 
    for(int i=0;i<[array count];i++) 
    { 
     NSMutableDictionary *tempDict=[array objectAtIndex:i]; 
     NSString *possibleText=[tempDict objectForKey:@"mainNote"]; 
     if([possibleText isEqualToString:targetText]) 
     { 
      //found match, replace tempDict with targetDict 
      tempDict=targetDict; 
      NSLog(@"found match"); 
      NSString *authorName=[[arrayOfNotes objectAtIndex:0] objectForKey:@"authorName"]; 
      NSLog(@"%@", authorName); //should be steve 
      return; 
     } 
     //no match, search sub notes 
     ... 
    } 
} 

回答

3

取代

tempDict=targetDict; 

[array replaceObjectAtIndex:i withObject:targetDict]; 

[tempDict setDictionary:targetDict] 

tempDict是一個指針,指向的NSMutableDictionary,但將其分配給另一個實例不意味着改變t的內容他以前的實例

你要修改什麼「指針指向」沒有「指針」,這就是爲什麼你可以使用setDictionary:做了「分配」

+0

啊是的,我認爲這解決了issue..thanks! – Snowman 2012-02-09 06:25:34

0

tempDict是剛剛的匹配元素的引用陣列。改變它的值不會修改數組。更換

tempDict=targetDict; 

[array replaceObjectAtIndex:i withObject:targetDict];