我在纠结于下面的代码。我不知道是怎么回事。
代码被评论为与崩溃有关:
- (IBAction) SavePreset: (id) sender
{
NSString *presetName = [nameCombo stringValue]; // nameCombo is a NSComboBox*
NSUserDefaults *vmDefaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *projectionPresets = [vmDefaults objectForKey: kVmGeorefPresetKey];
BOOL doSave = YES;
NSString *dictEntry = [projectionPresets objectForKey: presetName];
if (dictEntry) {
// this branch is not tested yet, plan to test when the rest is working.
int userChoice;
userChoice = NSRunAlertPanel( @"Save Preset",
@"This preset (%s) already exists, modify?",
@"OK", @"Cancel", nil, presetName);
doSave = (userChoice == NSAlertDefaultReturn);
if (doSave) {
[nameCombo addItemWithObjectValue: presetName];
}
}
if (doSave)
{
// projParamText is of class NSTextField*
NSString *presetParam = [projParamText stringValue];
// Up to this point, everything works as expected
// But, the following statement crashes silently.
[projectionPresets setObject: presetParam forKey: presetName];
// and the subsequent code is never executed
[savePresetButton setEnabled: NO];
}
}
我想知道从[nString String Value]返回的HeSnString是否返回一个指向内部字符串重新遍历的指针或一个新的NString,如果我稍后编辑NSTEXPIED的文本,它将不会改变。
最佳答案
找到了罪犯。以下声明来自nsuserdefaults文档:
从nsuserdefaults返回的值是不可变的,即使您设置了
可变对象作为值。例如,如果设置可变字符串
作为“mystringdefault”的值,稍后检索的字符串
使用stringforkey:将是不可变的。
解决方法是从旧的不可变词汇表创建一个新的预设词汇表,修改它并用用户默认值存储它。
关于objective-c - NSMutableDictionary setObject:forKey出现问题-崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7413603/