NSArray writeToFile返回“已弃用” - iPhone SDK

时间:2010-07-15 17:51:13

标签: objective-c ios4

我正在尝试将我的应用中的某些设置保存到plist文件中,然后在应用启动时加载它们。我在NSArray中保存了4个数字,称为数组。加载工作正常,因为如果我更改文件,应用程序将以文件更改的方式启动。

此代码可以正常工作:

- (void)LoadSettings {
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:kSaveFileLocation];
NSArray *array = [[NSArray alloc] initWithContentsOfFile:finalPath];
clockFaceImageSlider.value = [[array objectAtIndex:0] integerValue];
HourTypeSwitch.on = [[array objectAtIndex:1] integerValue];
touchRotationSwitch.on = [[array objectAtIndex:2] integerValue];
accelerometerRotationSwitch.on = [[array objectAtIndex:3] integerValue];
}

此代码适用于保存行:

- (void)SaveSettings {
    NSString *path = [[NSBundle mainBundle] bundlePath];
    NSString *finalPath = [path stringByAppendingPathComponent:kSaveFileLocation];
    NSArray *array = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:clockFaceImageSlider.value], [NSNumber numberWithInt:HourTypeSwitch.on], [NSNumber numberWithInt:touchRotationSwitch.on], [NSNumber numberWithInt:accelerometerRotationSwitch.on], nil];

    if (![array writeToFile:finalPath atomically:YES]) {
        NSLog(@"error");
    }
    //The log does print error
}

有人知道如何将它保存到plist中吗?

〜感谢

2 个答案:

答案 0 :(得分:4)

不要写数组描述NSString,而只需编写数组:

[array writeToFile:finalPath atomically:YES];

或者如果你想要字符串,你应该使用编码类型

NSError *error;
[[array description] writeToFile:finalPath atomically:YES encoding:NSUTF8StringEncodingerror:&error];

但这不会写一个plist。

答案 1 :(得分:2)

不要使用description的{​​{1}}(NSString}并将其写入文件,而只需使用NSArray本身的writeToFile:atomically ,如

NSArray

[array writeToFile:finalPath atomically:YES]; 的{​​{1}}被弃用的原因是它没有正确地考虑字符编码。谁告诉你使用writeToFile:atomically:?那个人/书应该受到惩罚......

也就是说,如果您只想保存几个条目,那么使用NSString会更容易,请参阅here。那么你所要做的就是

description

并且框架可以完成从准备幕后的plist路径到将其保存到磁盘的所有功能。

相关问题