NSMutableDictionary问题setObject:forKey - 崩溃

Agn*_*len 3 cocoa objective-c nsmutabledictionary

我正在努力使用以下代码.我并不希望它有什么问题.针对崩溃对代码进行了评论:

- (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];
}

}
Run Code Online (Sandbox Code Playgroud)

我想知道从[NSControl stringValue]返回的NSString*是否返回指向内部字符串reperesentaion或新NSString的指针,如果我稍后编辑NSTextField的文本,它将不会更改.

Agn*_*len 5

找到了罪魁祸首.以下声明来自NSUserDefaults文档:

即使您将可变对象设置为值,NSUserDefaults返回的值也是不可变的.例如,如果将可变字符串设置为"MyStringDefault"的值,则稍后使用stringForKey:检索的字符串将是不可变的.

解决方法是从旧的不可变的创建一个新的预设序列,修改它并将其存储回用户默认值.