David Janes' Code Weblog

March 23, 2009

iPhone How To: load a plist

code fragments,iphone · David Janes · 6:46 am ·

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 actually NSDictionary, which is the other common option

9 comments

  1. John Meyer · 2010-01-28 08:29

    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.

  2. David Janes · 2010-01-30 08:55

    I’m not sure it gets any easier than that above.

  3. 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?

  4. David Janes · 2010-05-07 09:22

    I’m very much of the opinion these days that one should avoid plists and use JSON instead!

  5. Apple still uses pList everywhere.

  6. 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.

  7. [...] How to load a plist (link) [...]

  8. Gaurav · 2012-02-15 14:29

    Hello , thanks for the tutorial , how can i load if i have multiple array .. like arraywitharray type of thing … i have a contact list with name and phone number of the contact so how can i have one array having the name and another array having the phone number only ? Thanks for the help

  9. Ariel Jakobovits · 2012-06-22 00:34

    Thanks for this. Might also point out that you can load an NSDictionary this way, too.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress

Switch to our mobile site