iPhone SDK: Dealing with .plist Files
Loading Contents of .plist file to an Array
The most straightforward method for dealing with .plist files is +[NSArray initWithContentsOfFile:path]. However, you need to specify the correct path of the plist file via [NSBundle pathForResource:plist ofType:].
Loading to a Dictionary
To load the contents of a .plist file to a dictionary, instantiate a NSDictionary or NSMutableDictionary and initialize it with [NSDictionary initWithContentsOfFile:]
- (NSDictionary *)dictionaryFromPlist: (NSString *)plist {
NSString *path = [[NSBundle mainBundle] pathForResource:plist ofType:@"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
return dict;
}Writing to a .plist
The easiest way to write values to a .plist file is to use a NSDictionary and modify its contents using -[NSDictionary setObject: forKey:]. To save the contents to a .plist file, use -[NSDictionary writeToFile: atomically:].
Atomically writing to a file guarantees that the file, if it exists at all, does not become corrupted even when the system should crash while writing.
NSString *path = @"Path to Plist.plist";
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
[dict setObject:@"Gierad" forKey:@"name"];
[dict writeToFile:path atomically:YES];Lastly, if you want to read/write small configurations for your app, NSUserDefaults is recommended. It contains methods to easily handle key-value pairs including floats and other objects.


