2010-07-15 48 views
2

我试图从应用程序保存一些设置为plist文件,当它关闭时,然后在应用程序启动时加载它们。我有4个数字保存在一个叫做数组的NSArray中。加载工作正常,因为如果我更改文件,应用程序将启动文件更改的方式。NSArray writeToFile返回“已弃用” - iPhone SDK

此代码工作正常:

- (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

而不是采取description(这是一个NSString)的NSArray,并把它写入一个文件,只是使用的NSArray本身writeToFile:atomically,如

[array writeToFile:finalPath atomically:YES]; 

原因的NSStringwriteToFile:atomically:已被弃用的它不能正确说明字符编码。谁让你用description?那个人/书应该受到惩罚......

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

[[NSUserDefaults standardUserDefaults] setObject: ... forKey:@"..."] 

和框架做了一切从准备一个plist路径幕后保存到磁盘。

+0

感谢它的工作。我只有4个值来存储。 – 2010-07-15 18:34:24

4

不要写入阵列的描述的NSString,只写而非阵列:

[array writeToFile:finalPath atomically:YES]; 

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

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

但这不会写一个plist。

+0

感谢您的快速回复。我不再收到错误,但它不是保存。我修改了我的代码,检查是否保存,并返回错误消息。我已经更新了我的问题。 – 2010-07-15 18:06:20

+0

你必须在你的应用程序的Documents目录中编写你的文件。这是您获得许可的唯一地方。 NSString * documentsDirectory = [NSHomeDirectory()stringByAppendingPathComponent:@“Documents”];是你想要保存你的东西的文件夹。 – nacho4d 2010-07-15 18:25:12

+0

感谢它的工作。 – 2010-07-15 18:40:16