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 print error
}
Does anybody know how I can make it save to the plist?
~thanks
Instead of taking the
description(which is anNSString) of anNSArrayand write it to a file, just usewriteToFile:atomicallyofNSArrayitself, as inThe reason
writeToFile:atomically:of anNSStringis deprecated is that it doesn’t correctly account for the character encodings. Who told you to usedescription? 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 isand the framework does everything from preparing a plist path behind the scenes to saving it to the disk.