Reading a plist into an NSArray

Mon, Nov 9
Reading a plist into an NSArray

This is the second tip in a series of four that is based on content from the O’Reilly book Head First iPhone Development. The first tip described how to adjust textfields that are hidden when the onscreen keyboard is shown.

Head First iPhone DevelopmentO’Reilly and iPhone Developer Tips are collaborating to give away a free ebook (electronic copy) of Head First iPhone Development each Friday in November. You can register in this weeks drawing by referring a friend to this iPhone Developer tip – see the Refer-a-Friend button near the bottom of this post. You can read more about last weeks winner, Bill Mietelski, on this post.

This tip, based on content in Chapter 4 – Multiple View, shows how to read a plist from a file in the resource bundle, into an array.

Hardcoded Array

Based on the example in the book, let’s assume we are keeping a list of mixed drinks inside our application. Somewhere in the initialization process we might write something like the following to build an array of NSString values:

NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:
    @"Firecracker", @"Lemon Drop", @"Mojito", nil];
 
// Show the string values  
for (NSString *str in array)
  NSLog(@"%@", str);
Creating a plist

Although the code above works, a better solution would be to keep the list of values in a plist as part of the resource bundle, then read the plist into an array.

To create plist, in Xcode, right click on Resources then select Add, New File, Mac OS X, Resource, Property List. Name the file DrinkArray.plist. Change the root type to Array and then add the four string values shown below:

Reading a plist into an NSArray

Reading the plist into an array is straight forward:

// Path to the plist (in the application bundle)
NSString *path = [[NSBundle mainBundle] pathForResource:
    @"DrinkArray" ofType:@"plist"];
 
// Build the array from the plist  
NSMutableArray *array2 = [[NSMutableArray alloc] initWithContentsOfFile:path];
 
// Show the string values  
for (NSString *str in array2)
  NSLog(@"--%@", str);
plists and Other Data Types

One of the benefits of working with plists, is that other types, for example NSDictionary, can be read from a plist. This means that you can create more complex data collections in a plist, such as an array of dictionaries.

For example, the plist below is also an array, however, the third value in the array is a dictionary.

With plists you can build various data types needed by your application and read those values directly into your program.

18 comments

i am using a plist in this way in my app but what i really need to know is how can i make it so the user of the iPhone can add and delete strings in the plist. Can you help please?

by dan on Dec 9, 2009. #

Dan,

There is no built in means to allow a user to add/delete entries in the plist. You will need to come up with a means for users to specify values to add and then write those to a plist. Same applies to deleting, you’ll need to have a way for a user to tell you which entries to delete, then write the code to delete those values.

by John Muchow on Dec 9, 2009. #

I’m having an issue with:

for (NSString *str in array2);

I get an error that says “local declaration of ‘array2′ hides instance variable.”

by Chris on Nov 6, 2010. #

Chris, check that you don’t have an instance variable (in the .h file) that has the name array2.

by John Muchow on Nov 6, 2010. #

Hi John,

I need to have a suggestion on using plist files in an iPhone native app.

I had a scenario to cache data between every close and re-open of the application. I want to show the user this content in an offline scenario.

So I had the following options to go with :

i) Sqlite Db: Creating tables and inserting. AFAIK What I feel is, more transaction with sqlite db would slow down the app, as there would be a bit of huge data.

ii) Core Data:
iii) NSUserDefaults : As of my experience, I don’t think this is preferable at all.

iv) PLIST : Storing all the data in the plist format (as we are getting the data in the xml format only till now)

So I need a suggestion from you, what would be the better way to go for caching the huge content , between every close and reopen of the application.

Awaiting reply .
Thank you.

by Pramod Jain on Dec 6, 2010. #

So, did you got any feasible solution to the above solution ?Since i am also facing the same issue. Though i am looking to have it by .plist file.

by Ajay on Feb 1, 2012. #

I already have my plist stored in an NSString.
How do I get it into an NSArray?

I’m currently doing this (sloppy) method:
> Save the plist string to a temp file.
> Reload the plist from the temp file using initWithContentsOfFile.
> Delete the temp file.

Any simple way to going directly from “pList in NSString” into an NSArray?

by jill on Feb 28, 2011. #

I want to push the values from plist to table.

by Pradeep on Aug 23, 2011. #

haiiiiiiiiiiii, it is very simple.

by Sajan on Aug 23, 2011. #

it’s very nice to understand about the plist reading and writing
give more assignments about the plist data appending and deleting the data from the plist

by narender on Sep 19, 2011. #

How does one get the plist file into the app bundle/resources in XCode 4? There is no Resources group in my project – the generated plist is just in “Supporting Files”.

Tx

by Janene on Oct 1, 2011. #

In Xcode 4, the default location of the application’s plist file nows appears to be the Supporting Files folder. Is there an issue with the build not working?

by John Muchow on Oct 2, 2011. #

The code runs but the array is empty. I can’t tell if the file is not found or some other error occurs. Ideas welcome. Janene

ps – I thought I’d replied already… sorry if there are 2 replies!

by Janene on Oct 3, 2011. #

Hi,

Can anyone help me how to save the user selected array using checkmarks in a table view ? I want to display the user selected data in another view by saying the list of items you have selected are apple,strawberry,banana.
From an array of let’s say 12 fruits. I am new to this ios programming, so please help me.

by jessy on Oct 20, 2011. #

Thanks a lot for the tutorial!

I was facing problem managing my plist when the root was a dictionary which doesn’t show inside Xcode. So I changed it in the property list editor then imported it to Xcode again.

Thanks again.
Mohammed

by Mohammed on Nov 9, 2011. #

I’m having troubles with the code, the array is always empty. I’ve checked the location where it stores the plist and it’s ok:

/Users/UserName/Library/Application Support/iPhone Simulator/4.3/Applications/A9BCF093-ABC1-4AC0-8E75-4316739E5B45/ApplicationName.app/DrinkArray.plist

I’ve tried to write items into the plist trough code:

- (void)writePlist
{
NSMutableArray *anArray = [[NSMutableArray alloc] init];
[anArray addObject:@"Milmers"];
[anArray addObject:@"Xcode"];
NSString *path = [[NSBundle mainBundle] pathForResource:@”DrinkArray” ofType:@”plist”];

// [anArray writeToFile:[self dataFilePath] atomically:YES];
[anArray writeToFile:path atomically:YES];

}

and that’s how it works, but if I read it without writing, it doesn’t, the array is always empty. What I’m doing wrong?

by phynet on Nov 14, 2011. #

What you are doing is right. You have to write the array to file path in order to read it. If you don’t write it to plist file path that means there are no entries (list of array) in the plist. I hope It’ll help u.

by jessy on Nov 16, 2011. #

Hello , i have a plist which have a dictionary then it having the name and phone number …

how can i load the plist in array such that
1 – one array has all the contact names
2- second array has all the phone numbers

Please help thanks

by Gaurav on Feb 15, 2012. #