Christopher
Stoll

iOS Snippet: Simple plist

For small apps you often need to store some basic settings, and using a plist file in the app’s document directory is an easy way to accomplish this. Below is a little snippet that I have used more than once for this purpose.

- (void)readAppSettings {
	NSString *plistPath = [NSSearchPathForDirectoriesInDomains
		(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
	plistPath = [plistPath stringByAppendingPathComponent:@"ticjitsu-
		settings.plist"];
	
	NSFileManager *fileManager = [NSFileManager defaultManager];
	
	if (![fileManager fileExistsAtPath:plistPath]) {
		NSString *sourcePath = [[NSBundle mainBundle] 
			pathForResource:@"ticjitsu-settings" ofType:@"plist"];
		[fileManager copyItemAtPath:sourcePath toPath:plistPath error:nil];
	}
	
	scoresDictionary = [NSMutableDictionary dictionaryWithContentsOfFile:
		plistPath];
	
	NSNumber *computerSkillNumber = scoresDictionary[@"settingComputerSkill"];
	_computerSkill = [computerSkillNumber integerValue];
	_gameWinsNone = scoresDictionary[@"gameWinsNone"];
}

- (void)saveAppSettings {
	NSString *plistPath = [NSSearchPathForDirectoriesInDomains
		(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
	plistPath = [plistPath stringByAppendingPathComponent:@"ticjitsu-
		settings.plist"];
	
	NSNumber *computerSkillNumber = [NSNumber numberWithInt:_computerSkill];
	[scoresDictionary setValue:computerSkillNumber 
		forKey:@"settingComputerSkill"];
	[scoresDictionary setValue:_gameWinsNone forKey:@"gameWinsNone"];
	[scoresDictionary writeToFile:plistPath atomically:YES];

}
Published: 2013-11-26
BloggeriOS 7iOSCodeSnippet