【问题标题】:reading plist file crashes读取 plist 文件崩溃
【发布时间】:2012-09-04 16:39:51
【问题描述】:

读入确实加载:

 NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath: path]) //4
{
    NSString *bundle = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]; //5

    [fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
}

//load in text fields.
NSMutableDictionary *savedData = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

nameField.text = [[savedData objectForKey:@"name"] stringValue];
locationTextField.text = [[savedData objectForKey:@"location"] stringValue];
sectorTextField.text = [[savedData objectForKey:@"sector"] stringValue];

在按钮点击时写入:

    - (IBAction)writingButton:(id)sender
{
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

    //[data setObject:[NSNumber numberWithInt:value] forKey:@"value"];
    [data setObject:[NSString stringWithString:nameField.text] forKey:@"name"];
    [data setObject:[NSString stringWithString:locationTextField.text] forKey:@"location"];
    [data setObject:[NSString stringWithString:sectorTextField.text] forKey:@"sector"];
}

plist 文件:

错误:

2012-09-04 17:03:40.360 应用程序[4849:c07] -[__NSCFString stringValue]: 无法识别的选择器发送到实例 0x6aa38f0 2012-09-04 17:03:40.362 应用程序 [4849:c07] *** 由于未捕获而终止应用程序 异常'NSInvalidArgumentException',原因:'-[__NSCFString stringValue]: 无法识别的选择器发送到实例 0x6aa38f0'

有什么想法吗?干杯。

【问题讨论】:

  • 另外,请阅读错误信息。它是简单易懂的英语。
  • 我不知道 id 我需要一个不同的选择器(我已经在 cocos2d 之外使用 ios 应用程序大约一个半月了,所以我还在学习)
  • plist 中的值已经是 String 类型,那你为什么要使用 [[savedData objectForKey:@"name"]stringValue] 对它们进行类型转换。只需使用 [[savedData objectForKey:@"name"] 等等。
  • @dev6546 我明白了 :) 但是,在 NSDictionary 的文档中,它仍然清楚地说明了它是如何工作的。

标签: objective-c ios plist read-write


【解决方案1】:

字典直接存储 NSString 对象 - 无需调用名为 - stringValue 的(不存在的)方法。简单写

nameField.text = [savedData objectForKey:@"name"];

等等。

(为什么你认为这个方法调用是必要的?)

【讨论】:

  • 非常感谢,您知道为什么我的按钮单击中的代码不起作用吗?现在阅读工作正常,但写作不是,我也尝试将代码移动到 didClose 但我对此也不满意。
  • @dev6546 “写入不起作用”是什么意思? NSMutableDictionary 集合中的值不是吗?
  • 这三个都是 uiTextFields 两个都设置在:-(void)pickerView:(UIPickerView *)thePickerview didSelectRow:(NSInteger)row inComponent:(NSInteger)组件,最后只是用键盘设置。当我关闭并打开应用程序时,它们并没有保存。它从我的资源文件夹中的 plist 文件中加载那些。
  • @dev6546 当然不是。你没有写出字典的内容。设置字典的内存实例的值显然不会改变文件本身的值。此外,您无法更新/写入应用程序包中的文件(出于安全原因,它是只读的) - 您必须将 plist 文件存储在 Documents 或 Library 目录中,然后使用 NSDictionary 的 writeToFile:atomically: 方法实际保存更改。
猜你喜欢
  • 1970-01-01
  • 2012-02-04
  • 1970-01-01
  • 2013-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多