【问题标题】:Problem with NSMutableDictionary setObject: forKey - crashesNSMutableDictionary setObject 的问题:forKey - 崩溃
【发布时间】:2011-09-14 08:48:22
【问题描述】:

我正在努力使用以下代码。我不认为它有什么问题。 代码针对崩溃进行了注释:

- (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* 是返回一个指向内部字符串 reperesentaion 的指针,还是一个新的 NSString,如果我稍后编辑 NSTextField 的文本,它不会改变。

【问题讨论】:

  • 它无声地崩溃?没有任何异常或错误?你用断点测试了吗?
  • 你能在调用stringValue之后检查调试器的presetParam类型吗?另外,请向我们展示任何崩溃日志输出

标签: objective-c cocoa nsmutabledictionary


【解决方案1】:

找到罪魁祸首。以下语句来自 NSUserDefaults 文档:

从 NSUserDefaults 返回的值是不可变的,即使你设置了 可变对象作为值。例如,如果您设置一个可变字符串 作为“MyStringDefault”的值,您稍后检索的字符串 使用 stringForKey: 将是不可变的。

解决方法是从旧的不可变字典创建一个新的预设字典,对其进行修改并将其与用户默认值一起存储。

【讨论】:

    【解决方案2】:

    试试[projectionPresets setValue: presetParam forKey: presetName];

    另外 NSLog 你的 presetName 和 presetParam 并查看其中是否有任何 nil 值。

    【讨论】:

      【解决方案3】:

      要在 NSMutableDictionary 中设置对象,您必须先做

      NSMutableDictionary *projectionPresets = [[NSMutableDictionary alloc] init];
      

      那么只有你可以为 NSMutableDictionary 设置对象。可变字典应该是绝对可变的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多