2012-02-09 4 views
0

私がやっているのは、特定のターゲット辞書の辞書の配列を検索し、見つかった場合は元の配列の実際の辞書をターゲット辞書に置き換えます。検索アルゴリズムは機能しますが、辞書のコピーは行いません。 「ポインタを使ってNSMutableDictionaryをコピーする

tempDict=targetDict;

著者名をログに記録しようとしたとき、私はtempDictは、元の配列から、元の辞書へのポインタをだろうと期待していたが、私は得る:問題のメインラインは言うものです「steve」の代わりに「moe」を使用します。

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

[array replaceObjectAtIndex:i withObject:targetDict]; 

又は

[tempDict setDictionary:targetDict] 

tempDictと

tempDict=targetDict; 

はNSMutableDictionaryへのポインタで置き換えるが、別のインスタンスに割り当てない変化を意味しませんtの内容彼あなたが「割り当て」を行うためにsetDictionary:を使用することができますなぜあなたはない「ポインタ」「へのポインタポイント」何を変更する必要があり、以前のインスタンス

は、thatsの

+0

tempDict=targetDict; 

を交換してはいああ、私はこれがissue..thanksを解くと思います! – Snowman

0

tempDictはのマッチした要素への参照だけですアレイ。その値を変更しても配列は変更されません。

[array replaceObjectAtIndex:i withObject:targetDict]; 
関連する問題