Saving objects to a file
April 27th, 2009
In many applications you may need to save settings and reload them at various points. A nice way to do this is using a plist (property list) file, and assigning objects to keys.
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); NSString* docDir = [paths objectAtIndex:0]; NSString* file = [docDir stringByAppendingString:@"/settings.plist"]; // To get objects NSString* errorDesc = nil; NSPropertyListFormat format; NSData* plistXML = [[NSFileManager defaultManager] contentsAtPath:file]; NSDictionary *temp = (NSDictionary*)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc]; NSString* savedText = [temp objectForKey:@"Saved_Text"]; float savedFloat = [[temp objectForKey:@"Saved_Float"] floatValue]; int savedInt = [[temp objectForKey:@"Saved_Int"] intValue]; // To set objects NSMutableDictionary* rootObj = [NSMutableDictionary dictionaryWithCapacity:1]; [rootObj setObject:savedText forKey:@"Saved_Text"]; [rootObj setObject:[[NSString alloc] initWithFormat:@"%f",savedFloat] forKey:@"Saved_Float"]; [rootObj setObject:[[NSString alloc] initWithFormat:@"%d",savedInt] forKey:@"Saved_Int"]; NSString* errorDesc; NSData* plistData = [NSPropertyListSerialization dataFromPropertyList:rootObj format:NSPropertyListXMLFormat_v1_0 errorDescription:&errorDesc]; if(plistData) [plistData writeToFile:file atomically:YES];
It also very good practice to store the settings file in the documents directory, lest it be overwritten by an update in the resources directory.