Sunday, March 20, 2011

Loading NSArray or NSDictionary with plist file

The content of NSArray and NSDictionary can be loaded from plist file.
The following steps can be used to do that:
1. Create the plist file, by adding new property List file from the resource option.

2. By default, the newly created property list file is of type dictionary <dict>. Change it to array <array> if NSArray is needed. Add in the key and value for dictionary or value for array.

3. The plist file can be loaded to the array using the dictionaryWithContentOfFile or arrayWithContentOfFile method. Typically it is loaded in the viewDidLoad method in the UIViewController.

Eg: For NSDictionary
NSString *path = [[NSBundle mainBundle] pathForResource:@"name" ofType:@"plist"];
NSMutableDictionary *dictionary=[NSMutableDictionary dictionaryWithContentOfFile: path];
Eg: For NSArray
NSString *path = [[NSBundle mainBundle] pathForResource:@"name" ofType:@"plist"];
NSMutableArray *arry=[NSMutableArray arrayWithContentOfFile: path];

4. The writeToFIle method can be used to write back changes to the plist for the array or dictionary object.
Eg: For NSDictionary
[dictionary setVale:value forKey:@"key"];
[dictionary writeToFile: path automatically: YES];

1 comment:

  1. it should be dictionaryWithContentsOfFile and arrayWithContentsOfFile. Note that it's Contents (with the s)