Loading data from .plist files

  • Twitter
  • Facebook
  • Digg
  • Reddit
  • StumbleUpon
  • del.icio.us
  • Google Bookmarks
February 14th, 2009 Posted by: - posted under:Snippets

Saving and Reloading from .plist files…

A great way to store dictionary data that does not change during runtime is in a .plist file. Say you want to organize some data hierarchically or you want to store the navigation structure of a drill-down somewhere more convenient (see drill-down save example in apple docs), then a .plist file is a great way to go.

Here’s a quick example of how to restore data from a plist file. I’ll use a plist file that you can find in every app out there: Info.plist

Sometimes it’s useful to display a version number on a splash view and here’s how you can do that using the Info.plist CFBundleVersion value.


NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"Info.plist"];
NSDictionary *plistData = [[NSDictionary dictionaryWithContentsOfFile:finalPath] retain];

versionLabel = [[UILabel alloc] initWithFrame:CGRectMake(100,100,60,25)]; // for example
versionLabel.backgroundColor = [UIColor clearColor];
versionLabel.textColor = [UIColor whiteColor];
versionLabel.font = [UIFont systemFontOfSize:10];
NSString *versionString = [NSString stringWithFormat:@"v%@", [plistData objectForKey:@"CFBundleVersion"]];
versionLabel.text = versionString;
[self.view addSubview:versionLabel];

Now you can see pretty easily how the plist file becomes an NSDictionary object. Pretty easy no?

  • Ron Holmes

    Very cool!

    I’d been using plist files to write settings, but didn’t realise I could just use the included plist file!

    Thanks.

  • RoMa

    Nice ;)
    Thanks for all tutorials brandon.
    When will you write the end of the game’s tutorial ?

  • Kenneth

    You can just use:

    NSString* versionString = [[NSBundle mainBundle] objectForInfoDictionaryKey:@”CFBundleVersion”]

  • Mark

    i need to create a seperate class to load the localized strings from the resources…. i dont want to use the existing macro functions to load it..

    Is it possible???

    If so , can u suggest some ideas how to do it?

    Thanks

  • http://www.onemoretap.com XCool

    Can I use these PLIST files to store any other data? Is it possible to modify the Fruits app (that uses array) to use PLIST files instead? Is this the right method?

  • Stelian Iancu

    Sure, you can store any data you want into a plist file. We are using a plist for storing the settings of our application (for various reasons we can’t use the global settings app).

  • rey

    I realize this is a slightly unrelated question. How do you access or reference a variable from a different view or delegate? But I suppose it is somewhat related, because in the absence of figuring out how to do that I might have to save something to a plist in one view just to get access to it in another.

  • Walter

    I am also thinking of using the plist instead of sqlite3 to hold some static data that I will use to populate some array objects at runtime like XCool. Is there any reason not to do this?

  • http://afruj.wordpress.com/2009/03/24/iphone-tutorials/ iPhone development Tutorials « The Brook Song – ঝর্ণার গান

    [...] 39. Saving and Reloading from .plist files [...]

  • http://www.sun.ac.za Helmi

    I am having trouble in saving and then reloading floating point data out of a data.plist file. Is it possible to do ? I can do floating point data with the defaults list but not with a private data.plist ? Will it be possible to store floating point data in info.plist ?

  • http://www.oxinos.com Andreas

    Hey thanks for the tuto, great help, so i get the point of loading the data, lets say i save there some variables and i want with a timer to save update them, how i do that?
    (just the update code not the timer)

  • http://www.oxinos.com Andreas

    In fact my question is how i save into the existing plist, i create a plist with a dictionary which contains 3 strings, and an array with 2 items, i load them into my code, i use them fine, but how i can write into this fields in plist

  • http://www.oxinos.com Andreas

    I find my answer alone :p

    If anyone has this question email me to send you the source code to achieve that :p

    andreasoxinos@me.com my email

  • Aziza

    That’s pretty good… but what about sound files?? how can i read from plist paths of mp3 for example…?

  • VIKI

    This code doesn’t display work for me

  • Salim

    hi, can any one tell how to create .plist file dynamically..
    please any one have idea then please reply me on this email address.

  • Ramana

    First of all add a plist to your project in Xcode. For example “data.plist”.
    Next, look at this code which creates path to plist in documents directory:
    
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"]; //3
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath: path]) //4
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:@”dokument” ofType:@”plist”]; //5
    [fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
}
    1) Create a list of paths.
2) Get a path to your documents directory from the list.
3) Create a full file path.
4) Check if file exists.
5) Get a path to your plist created before in bundle directory (by Xcode).
6) Copy this plist to your documents directory.
    Ok, next read data:
    
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
    //load from savedStock example int value
int value;
value = [[savedStock objectForKey:@"value"] intValue];
    [savedStock release];
    And write data:
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
    //here add elements to data file and write data to file
int value = 5;
    [data setObject:[NSNumber numberWithInt:value] forKey:@”value”];
    [data writeToFile: path atomically:YES];
[data release]
    Remember about two things:
    1) You must create a plist file in your Xcode project.
2) To optimize your app, better is to save all the data when application (or for example view) is closing. For instance in applicationWillTerminate. But if you are storing reeaaaally big data, sometimes it couldn’t be saved in this method, becouse the app is closing too long and the system will terminate it immediately.

  • Ramana

    First of all add a plist to your project in Xcode. For example “data.plist”.

    Next, look at this code which creates path to plist in documents directory:

    
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
    
NSString *documentsDirectory = [paths objectAtIndex:0]; //2

    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"]; //3
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath: path]) //4
    
{


    NSString *bundle = [[NSBundle mainBundle] pathForResource:@”dokument” ofType:@”plist”]; //5

    [fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
    
}
    1) Create a list of paths.
    
2) Get a path to your documents directory from the list.
    
3) Create a full file path.
    
4) Check if file exists.

    5) Get a path to your plist created before in bundle directory (by Xcode).
    
6) Copy this plist to your documents directory.
    Ok, next read data:
    
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

    //load from savedStock example int value


    int value;
    
value = [[savedStock objectForKey:@"value"] intValue];
    [savedStock release];

    And write data:
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

    //here add elements to data file and write data to file

    int value = 5;
    [data setObject:[NSNumber numberWithInt:value] forKey:@”value”];
    [data writeToFile: path atomically:YES];
    
[data release];
    Remember about two things:
    1) You must create a plist file in your Xcode project.
2) To optimize your app, better is to save all the data when application (or for example view) is closing. For instance in applicationWillTerminate. But if you are storing reeaaaally big data, sometimes it couldn’t be saved in this method, becouse the app is closing too long and the system will terminate it immediately.

    I think this would be help full to you, @salim.

  • Hlen0800

    Hi,  i’m only a beginner in this environment, i just want to ask if it is possible to display the plist data saved from  other view to a  new view. I am now doing my first application, i used two UITextfied to saved data in the PList and it works fine. My problem is i don’t know how to display that two data input to the other view. To make it clear i input and saved data in EventViewController and I want that saved data to be displayed in PageViewController in one UITextField only.

  • http://twitter.com/jalencas victor jalencas

    You’re leaking the PList dictionary.

    And also, if you want the retained version, obtaining the autoreleased version and then retaining it is too much work. Just use initWithContentsOfFile: instead

blog comments powered by Disqus