繁体   English   中英

通过指针复制NSMutableDictionary

[英]Copying NSMutableDictionary through pointers

我想做的是在字典数组中搜索特定的目标字典,如果找到,则用目标字典替换原始数组中的实际字典。 搜索算法有效,但字典的复制无效。 有问题的主线是这样的:

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

更换

tempDict=targetDict;

[array replaceObjectAtIndex:i withObject:targetDict];

要么

[tempDict setDictionary:targetDict]

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

您必须修改“指针指向”而不是“指针”,这就是为什么您可以使用setDictionary:进行“分配”的原因

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

tempDict=targetDict;

[array replaceObjectAtIndex:i withObject:targetDict];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM