开发者

NSArray writeToFile returning "is deprecated" - iPhone SDK

I'm trying to save some settings from my app to a plist file when it closes, then load them when the app launches. I have 4 numbers saved in an NSArray called array. The loading works fine because if I change the file, the app starts the way the file was changed.

This code works fine:

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

This code works up to the save line:

- (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 pri开发者_JAVA技巧nt error
}

Does anybody know how I can make it save to the plist?

~thanks


Dont write array's description NSString, just write the array instead:

[array writeToFile:finalPath atomically:YES];

Or if you want the strings you should use en encoding type

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

but this will not write a plist.


Instead of taking the description (which is an NSString) of an NSArray and write it to a file, just use writeToFile:atomically of NSArray itself, as in

[array writeToFile:finalPath atomically:YES];

The reason writeToFile:atomically: of an NSString is deprecated is that it doesn't correctly account for the character encodings. Who told you to use description? That person/book should be punished...

That said, if you want to save just a few entries, it would be easier to just use NSUserDefaults, see here. Then all you have to do is

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

and the framework does everything from preparing a plist path behind the scenes to saving it to the disk.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜