Objective c NSMutableDictionary setObject的问题:forKey-崩溃
我正在努力学习下面的代码。我不知道它有什么毛病。 代码将针对崩溃进行注释:Objective c NSMutableDictionary setObject的问题:forKey-崩溃,objective-c,cocoa,nsmutabledictionary,Objective C,Cocoa,Nsmutabledictionary,我正在努力学习下面的代码。我不知道它有什么毛病。 代码将针对崩溃进行注释: - (IBAction) SavePreset: (id) sender { NSString *presetName = [nameCombo stringValue]; // nameCombo is a NSComboBox* NSUserDefaults *vmDefaults = [NSUserDefaults standardUserDefaults]; NSMutableDictionary *proj
- (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];
}
}
我想知道从[NSControl stringValue]返回的NSString*是返回指向内部字符串重新呈现的指针,还是返回一个新的NSString,如果我稍后编辑NSTextField的文本,它将不会更改 尝试
[projectionPresets设置值:presetParam-forKey:presetName]代码>
同时记录您的presetName和presetParam,查看其中是否有零值。找到了罪魁祸首。以下陈述来自NSUserDefaults文档:
从NSUserDefaults返回的值是不可变的,即使您设置了
可变对象作为值。例如,如果设置一个可变字符串
作为“MyStringDefault”的值,后面检索的字符串
使用stringForKey:将是不可变的
解决方法是从旧的不可变字典创建一个新的预设字典,修改它并使用用户默认值将其存储回去。要在NSMutableDictionary中设置对象,必须首先执行以下操作
NSMutableDictionary *projectionPresets = [[NSMutableDictionary alloc] init];
然后,只有您可以为NSMutableDictionary设置对象。可变字典应该是绝对可变的 它悄无声息地崩溃了?没有任何例外或错误?您是否使用断点进行了测试?在调用stringValue后,是否可以检查调试器中的presetParam类型?另外,请向我们显示任何崩溃日志输出