for ( int cnt = 0 ; cnt < nPeople ; cnt++ )
{
    ABRecordRef ref = CFArrayGetValueAtIndex(allPeople, cnt);

    NSString    *firstName  = (NSString *)ABRecordCopyValue(ref, kABPersonFirstNameProperty);
    NSString    *lastName   = (NSString *)ABRecordCopyValue(ref, kABPersonLastNameProperty);
    NSString    *fullName;

    /* skipped code at here : code to merge firstName and lastName to fullName. In my country, many of us don't separate first name and last name */

    // tempKeyString : NSString variable that has key of fullNameArray value for nameDictionary.
    // fullNameArray : to keep some fullName variables for tempKeyString.
    if (!tempKeyString) // there's no tempKeyString, a.k.a. it's the first fullName.
    {
        // it's not important to know about GetUTF8String:fullName. It's for my own language.
        tempKeyString = [self GetUTF8String:fullName];
        [fullNameArray addObject:fullName];
    }
    else
    {
        if ([tempKeyString characterAtIndex:0] == [[self GetUTF8String:fullName] characterAtIndex:0]) // if fullName has the same tempKey with fullNameArray.
        {
            [fullNameArray addObject:fullName];
        }
        else // if fullName has different tempKey with fullNameArray.
        {
            //tempKey : key data for fullNameArray
            NSString    *tempKey    = [tempKeyString substringToIndex:1];
            // tempDict : to keep the deep copy of nameDictionary before adding new key.
            NSDictionary *tempDict   = [nameDictionary mutableDeepCopy];
            // add new key (tempKey) with new value (fullNameArray)
            // PROBLEM : ALL values (including previous values) in dictionary(nameDictionary) are overwritten to a new value(fullNameArray).
            [nameDictionary setObject:fullNameArray forKey:tempKey];

            //empties fullNameArray so that it can get the new fullName of the new tempKey.
            [fullNameArray removeAllObjects];
            //refresh tempKeyString, and add the new fullName.
            tempKeyString = [self GetUTF8String:fullName];
            [fullNameArray addObject:fullName];
            ...
        }
    }
}

我正在尝试从iPhone的联系人中创建一个NSMutableDictionary对象。为什么要创建NSMutableDictionary类型的对象,是因为我需要联系人索引,而直接从ABAddressRef类型的对象创建索引看起来并不容易。我还需要使搜索功能..

当我刚刚编码时没有问题,但是在调试之后,唯一的问题使我发疯。将名为tempKey的键的名为fullNameArray的数组应用于namedDictionary之后,我可以发现nameDictionary具有与fullNameArray有关的所有值。 以前的所有数据都被覆盖! 我在应用fullNameArray并将其复制到较新的nameDictionary之前,尝试制作以前的nameDictionary的深度复制版本。但是,当我在第三行检查断点时,在tempDict上找不到先前的数据。

我添加了更多代码和注释。它可能比我的解释要有用的多。任何问题都令人高兴!

我试图整夜从这里找到原因-StackOverflow-和其他网页,但是我找不到任何类似的问题..请帮助我!提前非常感谢您!!

最佳答案

它被清空的原因是

[nameDictionary setObject:fullNameArray forKey:tempKey];

在这里,您使用对象“fullNameArray”设置字典,然后
[fullNameArray removeAllObjects];

删除此数组中的所有值,有效地删除“nameDictionary”中的对象,它们是同一对象,它不是存储在字典中的fullNameArray的深层副本。为什么您仍然需要将任何内容存储到阵列中?您只存储1个值。
[nameDictionary setObject:fullName forKey:tempKey];

会做你需要的。抱歉,如果我弄错了您的问题,很难理解

10-08 05:48