Im trying to save and load the settings of a simple application. However im still new to obj-c. I do believe the saving part is working, but not the loading part. When i change the settings, press back and reenter the settingsview, the settings are not loaded.
I think it's something with how the SettingsViewController is created with the saved data, but i cannot wrap my head around it.
Below is the interesting code from the SettingsViewController, and further below, from the MainWindowViewController
SettingsViewController:
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if(self)
{
NSString * path = [self settingsArchivePath];
self = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
shakeSwitch.on = shakeForTag;
[warningDistanceFld setText:[NSString stringWithFormat:@"%i",warningDistance]];
}
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder{
self = [super initWithNibName:@"SettingsViewController" bundle:nil];
if(self)
{
[self setShakeForTag:[aDecoder decodeBoolForKey:@"shakeForTag"]];
[self setWarningDistance:[aDecoder decodeIntForKey:@"warningDistance"]];
[self setMapType:[aDecoder decodeIntegerForKey:@"mapType"]];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeInt:warningDistance forKey:@"warningDistance"];
[aCoder encodeBool:shakeForTag forKey:@"shakeForTag"];
[aCoder encodeInteger:mapType forKey:@"mapType"];
}
-(NSString *)settingsArchivePath
{
NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentDirectory = [documentDirectories objectAtIndex:0];
return [documentDirectory stringByAppendingPathComponent:@"settings.archive"];
}
-(IBAction)back:(id)sender
{
if([mapChanger selectedSegmentIndex] == 0){
mapType = MKMapTypeSatellite;
}else if([mapChanger selectedSegmentIndex] ==1){
mapType = MKMapTypeHybrid;
}else{
mapType = MKMapTypeStandard;
}
NSString *warning = [warningDistanceFld text];
warningDistance = [warning intValue];
shakeForTag =shakeSwitch.on;
[self saveChanges];
[self dismissViewControllerAnimated:YES completion:nil];
}
-(BOOL)saveChanges
{
NSString *path = [self settingsArchivePath];
NSLog(@"saved");
return [NSKeyedArchiver archiveRootObject:self toFile:path];
}
Code in MainWindowViewController to initialize the settingsViewController:
svc = [[SettingsViewController alloc]initWithNibName:@"SettingsViewController" bundle:[NSBundle mainBundle]];
svc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:svc animated:YES completion:nil];