通过指针复制NSMutableDictionary

时间:2012-02-09 05:59:10

标签: iphone objective-c nsdictionary

我要做的是搜索特定目标字典的字典数组,如果找到,则将原始数组中的实际字典替换为目标字典。搜索算法有效,但字典的复制却没有。有问题的主线是:

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

2 个答案:

答案 0 :(得分:3)

替换

tempDict=targetDict;

[array replaceObjectAtIndex:i withObject:targetDict];

[tempDict setDictionary:targetDict]

tempDict是指向NSMutableDictionary的指针,但是将其分配给另一个实例并不意味着更改前一个实例的内容

你必须修改“指针指向”而不是“指针”的内容,这就是为什么你可以使用setDictionary:进行“赋值”

答案 1 :(得分:0)

tempDict只是对数组匹配元素的引用。更改其值不会修改数组。取代

tempDict=targetDict;

[array replaceObjectAtIndex:i withObject:targetDict];