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 类型的对象制作索引看起来并不容易。我还需要做搜索功能..
我刚编码的时候没有问题,但调试后唯一的问题让我抓狂。在我将名为 fullNameArray 的数组和名为 tempKey 的键应用于 namedDictionary 之后,我可以发现 nameDictionary 具有 fullNameArray 的所有值。 所有以前的数据都被覆盖了!在应用 fullNameArray 并将其复制到较新的 nameDictionary 之前,我尝试对以前的 nameDictionary 进行深度复制。但是,当我检查第三行的断点时,我在tempDict中找不到之前的数据。
我添加了更多代码和注释。它可能比我的解释更有帮助..任何问题都很高兴!
我试图从这里-StackOverflow-和其他网页找了一晚上的原因,但我找不到任何类似的问题..请帮助我!非常感谢您!!
最佳答案
之所以清空是因为
[nameDictionary setObject:fullNameArray forKey:tempKey];
在这里,您使用对象“fullNameArray”设置字典,然后
[fullNameArray removeAllObjects];
删除这个数组中的所有值,有效地删除“nameDictionary”中的对象,它们是同一个对象,它不是存储在字典中的 fullNameArray 的深拷贝。为什么你需要将任何东西存储到你的数组中?您只存储 1 个值。
[nameDictionary setObject:fullName forKey:tempKey];
会做你需要的。对不起,如果我弄错了你的问题,这很难理解
关于ios - 设置对象 :forKey: of NSMutableDictionary overwrites all data in dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8998125/