Property Lists – plists – are a standard way of storing data in iPhone and MacOS programs. Here’s how you use them on the iPhone.
Add this code to Controller.m to populate member listData with the data from plist dwarves.plist:
- (void) viewDidLoad
{
NSBundle* bundle = [NSBundle mainBundle];
NSString* plistPath = [bundle pathForResource:@"dwarves" ofType:@"plist"];
NSArray* dwarves = [[NSArray alloc] initWithContentsOfFile:plistPath];
self.listData = dwarves;
[dwarves release];
[super viewDidLoad];
}
To create the plist:
- open and select the Resources folder in Interface Builder
- right-click and select Add > New File…
- select Other in the popup (at the bottom)
- select the Property List icon and then press the Next button
- choose your name and Finish
To edit the plist:
- select it in the Resources Folder
- right-click and select Open with Finder
Make sure:
- the name of the plist in the code (
dwarves) is the same as the plist you created - the type of the plist in the code (
NSArray) is the same as the plist you created – by default it is actuallyNSDictionary, which is the other common option
Hey, thanks for the advice. Is there anyway you can send me the source code so I can understand it better? That would be extremely helpful.
I’m not sure it gets any easier than that above.
How would I also do this one:
I have an NSString that already cotains all my plist-text.
I want to break it up into its individual objects and store them in an array.
(Like initWithContentsOfFile can do.)
Currently, I find myself having to SAVE it… then just RELOADING it with initWithContentsOfFile.
Isn’t there a initWithContentsOfString somewhere?
I’m very much of the opinion these days that one should avoid plists and use JSON instead!
Apple still uses pList everywhere.
David,
Actually, plists are faster than anything else, especially in the case of using binary encoded plists. Apple uses them for the App Store/Apple Store/iTunes, and they’re extremely fast. Faster than JSON by a long shot.
[...] How to load a plist (link) [...]