Write/Read data to .plist file.

Hi!

I was struggling for a very long time with this feature and I was so angry that nobody put a complete code – just simple lines. I’ll hope this will be helpfull.

Why using plists? Becouse it’s simple, effective and comparing to NSUserDefaults very fast.

The main reason that many people failed with this, was the fact, they are trying to save data in Bundle Directory. It can’t be done, this place is protected and be a completed “one thing”. So the best option is to save your data into documents directory.

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:@”data” 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 hope it will help you :).

Responses

  1. Perfect! Simple and to the point. Just what I needed. Thanks.

  2. Awesome,
    I wish every blogger would ‘cut the crap’ and get to the point, like you do.
    good job.

  3. Like you said at beginning, other blogs fail to show the whole deal. You really helped me with this today, thanks!

  4. Thank you! very usefull code. regards.

  5. Hi,

    I would like to thank you for a great and COMPLETE tutorial.

    You just ended a bad week for me…….

    if you get this please email me so I can send you a coupon for my app.

    Cheers,

  6. Very, very helpful! It’s amazing how difficult this information was to find. Thank you so much for your post!

  7. Thanks!
    Very Helpfull post!

  8. OH! Thanks you very much!!
    It helps me alot !! :]

    Tak

  9. Excellent, I’ve been searching for a tutorial that clearly explains this. Great Job.

  10. [...] Write & Read data to .plist (link) [...]

  11. Good Tutorial if you have some experience, not so good if you don’t

    If you have some pictures it would be good or the code even better.

    Iain

  12. Great help! i cant explain how exhausted i was of searching help on this anymore !! Could u kindly explain how to read from the same plist on a new view?

    Thanks :)

  13. My example copy this site is not work.
    When the app to be this line ([fileManager copyItemAtPath:bundle toPath: path error:&error]; //6) show *** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘*** -[NSFileManager copyItemAtPath:toPath:error:]: source path is nil’
    *** Call stack at first throw:

  14. I’d like make with string … this example make with int… How should I do?

  15. Sorry for being thick, but I don’t get it :-( why are you searching for a path to “data.plist”, and if that doesn’t exist creating another path to a document called “dokument.plist”? Why can’t you just find the path of the first item and leave it at that?

  16. Hi Joe.

    Hoh there is probably a mistake:) not “dokument” but “data” should be.

    It works on this way:

    When you add “data.plist” file into your project it will be on your device in the bundle file. But you can’t save anything there. In bundle directory everything is protected. So first of all you are creating the path to the documents directory where it must be the plist file. If it doesn’t exist, just get the path of the plist file in bundle dir and copy it to documents dir.

  17. Brilliant, thanks so much!

    Makes perfect sense now :-)

  18. Hi, Thanks for this guide, it looks like it is just what I need.

    I am just wondering, is there any specific places in my project that it would be better to place this code than other?

    Thank you :)

    – Peter

  19. Hi Peter.

    Probably the app delegate class is the best place. Terminate and load method should be OK:).

    But for example in my opengl es applications I’m loading data in initWithCoder method. It still works :)

  20. Hi, thanks for the quick reply :) I did go ahead and put it in the app delegate ind the load didfinishlaunching and appwillterminate.

    But the problem is for me, that when I declare the path in the launch function, I get a “not declared in this scope” in the terminate function.

    Do you put the entire code in one function and then make calls to it or how do you excactly implement it?

    Is it possible that you can post the entire class where you implemented it?

    Thank you in advance :)

    -Peter

  21. Hi, I need an login app with the xml file which has created in the same computer.
    I have to login by the name and id given in xml file.
    smrafiqsmd@gmail.com

    Thanks

  22. Thanks very much.. exactly looking for this from long time

  23. Thank you! helped me sooo much!
    Thanks dude.

  24. Thank you so much!!!!!! Helped me a lot!!!! I can’t believe it!!

  25. This is cool! You should do a post on how to display this data in a UITableView.

  26. I tried to run the code and it ran successfully however i couldn’t see the data.plist file in my resource files. Does it physically create the plist file?

  27. Very useful point,

    I need one help,

    If I want to modify any array item in plist rather then add, what should I do ?
    Can you please help me ?

    Thanks & Regards.

  28. I am having trouble writing back to the plist.
    Root Dictionary
    Rows Array
    Item 0 Dictionary
    Title1 String
    Title2 String

    Trying to write to Title1 & Title2
    Paul

  29. On the line:

    [fileManager copyItemAtPath:bundle toPath: path error:&error]; //6

    it gives me a SIGABRT error. Is there any reason for this? I copied your code all to a function then ran the function. Has anyone else had this problem or know how to fix it? I’m using iOS 4.1.

    • scratch that, I just realized how to make a new plist. If I run into any other problems I’ll post back here. Thank you for this tutorial. :)

  30. i used this code segment and got the output fine in simulator but in device SIGABRT error occurs. can anyone help me?

  31. works perfect in device too.
    Thanks

  32. Its very userful but the little modification is required at line number 6

    path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat: @"mydata.plist"] ];

    then it will work perfectly……..

    Thank you

  33. @jamil bro i modified the line number 6 as i posted then there is no SIGABRT error

    try it ….

  34. Its very userful but the little modification is required at line number 6

    path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat: @"mydata.plist"] ];

    then it will work perfectly……..

    @jamil,Michael it also remove that SIGABRT error

    Thank you
    rajesh.pardeshi_161187@avibha.com

  35. @Raj Pardeshi: Is there a specific place where this code should be placed or can it be placed under any function? I have an application, where the data must be written into a file when I click the submit button. Can I put it in -(IBAction)Submit ? ( this is the action for the button submit ) ?

    Thank you

  36. Great Post! i’ll tweet this post, very helpful keep up the good work and thank you once more! :D

  37. Great tutorial. IF YOU COPY AND PASTE, you are likely to get an error at line
    NSString *bundle = [[NSBundle mainBundle] pathForResource:@”data” ofType:@”plist”]; //5

    The quotations around data and plist are italicized – my computer pasted them as a different character than standard quotations and I got a compilation error. Easy enough to fix but not completely obvious where the error is coming from. Comes up as “Stray @ in program” error. Think third section of code also has this problem.

  38. hi i am new to iphone programming and i am reading a book in which they had created a dictionary with names only i want to add meaning to them also and retrive them in a view controller please help me

  39. Thanks! That really helps.

  40. Thanks a lot!! It is very useful

  41. i’m trying to save sound/audio in plist also, but i don’t know if your code works for me. would you help me please? i’m very stuck for almost two weeks because of this, thanks

  42. Hey. This is great, I’ve been looking for a simple tut on how to do this.
    Very good work, mate :-)

  43. Bundle of thanx

  44. Good code
    Regards

  45. I used the codes just changing the

    int value = 5;

    [data setObject:[NSNumber numberWithInt:value] forKey:@”value”];

    to

    [data setObject: ipTextField.text forKey:@"IP"];

    in a method called save with no return type but nothing is going into my plist.
    Could you help me out?

  46. i will try to write data into plist but old data was loose and only one record is inserted.

  47. AWESOME !!!
    This is simple and perfect answer : )

  48. cheers !! just what i needed and works like a charm

  49. How about a mod to show how to write a binary pList ?

  50. it is really great tutorial. but can u show details of your plist here. i want to make something like that. so maybe it will be more helpful if i can see your plist strucutre

  51. hi i used ur code but my plist contain all garbage data with my data . will u plz give me suggestion to my query

  52. Thanks you very much!!!!!!

  53. thanks for the tutorial
    quick- simple and yet solves the problem…
    just like the way I like the code to be. :)

  54. omg… I spend week just for this complete and simple tutorial,even come with explanation.thank you.

    i hope this work with imageNamed.

  55. Same for me… a whole day going crazy just because Xcode 4 / IOS 5 does not allow to save in other directory than Documents. No other tutorial I found offered the solution. MANY THANKS.

  56. I love you and I want to marry you!

    Might be overstating it bit, but this is the simple example I needed to accomplish this for my app and I couldn’t find it succinctly demonstrated anywhere else.

    Thank you.

  57. Thanks dear for giving the complete code….

  58. No other tutorial offered this solution….Thanks for the detail description…

  59. Thanks! That really help full

  60. My tech director used to say “complexity is simple, simplicity is complex”. It took me longer to find this page on google than it did to understand and implement.

    You stand tall among the circus of obfuscation that is iOS development. Many thanks!

  61. Thanks..!

  62. I’d like to add to the chorus of thanks for this simple, useful, complete tip! I can now do what I need to do to save my game’s state. THANK YOU :-)

  63. thanks

  64. Thanks man! Really helps!

  65. This was a great tutorial. Thanks!

  66. Very useful post, thank you !

  67. thank you…

  68. Thanks. Much appreciated. Exactly what I was looking for.

  69. Awesome tutorial – straight to the point; Love it!

  70. Very useful post, thank you

  71. Thanks Mike T. I was wondering why the copy+pasta wasn’t working.

  72. Wow, It’s worked for me too.
    Great tutorial and to the point.

    Thanks & Good Luck Ahead

  73. hey !! awesome tutorial !! did it in minutes !
    thanks a lot !

  74. You saved my time lot. Thanks!..
    One small question.
    1. I couldn’t find myapp.plist file at my mainbundle resourcePath. Why?

  75. can you please help me..!!!
    It is working perfectly fine for normal objects but I need to insert an NSDictionary and retrieve… how can i do that???
    please

  76. Your style is really unique compared to other folks
    I’ve read stuff from. Thank you for posting when you have the opportunity, Guess I’ll just bookmark this web site.

  77. thanks alot

  78. succinct and on the bull’s eye…good job
    keep up the philanthropy mates….cheers

  79. Thank you for this good post.
    Helped me alot to load and store plist.

  80. Thanks so much. You save me from hours of debugging. Previously I didn’t even have any idea that there’s Bundle vs Document Path. My code is working now when I simulate with my device, thanks to you buddy.

  81. Make sure you put your keyword in the web page
    title, first paragraph and once or twice in the main body.

    You might get one or more benefits of outline designer along with it is the ideal means to unleash the capacities.
    If a picture is worth a thousand words then you can just image how much you will absorb by browsing this site.

  82. Cheers to your PROFITmatic Turnkey Automated
    Internet Profit Center,. He knew the system well enough to
    not pay many of his suppliers and sub-contractors, then would cover it up up by handing
    out fake lien releases to make it look like they were paid.
    Once safely at Thebes, though, the obelisks were brought
    to the temple at Karnak with much fanfare.

  83. Make sure you put your keyword in the web page title, first paragraph and once or twice in the main body.
    Wouldn’t it be easier if we could be able to save changes ourselves whenever we want. Html form builder renders efficient service to online business companies to create any sort of online form to integrate it into their website and receive incoming information from online visitors.

  84. Cheers to your PROFITmatic Turnkey Automated Internet Profit Center,.
    It’s easy to use a fake IP address on i – Phone and i – Pad, but you need to know what you need the fake IP for. The specific combination of reps, sets, exercises, and weight depends upon the desires of the body builder.

  85. Save All Paperwork: Whatever paperwork arrives with
    your parts or which is provided from the seller should be maintained.
    Wouldn’t it be easier if we could be able to save changes ourselves whenever we want. You can make corrections directly instead of having to search mistake through the code, if something does not seem OK for you.

  86. Really Thanks..Very Helpful to me..

  87. what about:
    use 2 or more data plist: data1.plist, data2.plist, data3.plist
    its posible in xCode?
    ppVen

  88. […] http://ipgames.wordpress.com/tutorials/writeread-data-to-plist-file/ […]

  89. Today, I went to the beachfront with my children.

    I found a sea shell and gave it to my 4 year old
    daughter and said “You can hear the ocean if you put this to your ear.” She put the shell
    to her ear and screamed. There was a hermit crab inside and it pinched her ear.
    She never wants to go back! LoL I know this is completely off topic but I had
    to tell someone!

  90. I understand that you have to retrieve data from plist first, add data, and rewrite the entire contents to the plist file.

    But my code here is NOT appending, but refreshing every time I call this method.

    – (void) saveDataToPlist {
    // Retrieve path and filename of the plist file
    NSString *myColorsListFile = [self dataFilePath];

    NSMutableArray *innerArray1;
    NSString *error;

    UserGivenColorHexString = HexTextField.text;
    NSMutableDictionary *rootObj = [NSMutableDictionary dictionaryWithCapacity:100];

    if ([[NSFileManager defaultManager] fileExistsAtPath:myColorsListFile]) {
    // File exists
    rootObj = [[NSMutableDictionary alloc] initWithContentsOfFile:myColorsListFile];

    [innerArray1 addObjectsFromArray:[NSMutableArray arrayWithContentsOfFile:myColorsListFile]];
    [innerArray1 addObject:UserGivenColorName];

    } else {
    // Create file
    rootObj = [[NSMutableDictionary alloc] init];

    innerArray1 = [NSMutableArray arrayWithObjects: UserGivenColorName, nil];
    [rootObj setObject:innerArray1 forKey:@"ColorName"];
    }

    id plist = [NSPropertyListSerialization dataFromPropertyList:(id)rootObj format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];

    [plist writeToFile:myColorsListFile atomically:YES];
    }

  91. Thank you, great tutorial!

  92. Great job! It think you will help a lot of people with this! Thank you I know it helped me. By the way to everyone else, you can find me by searching nerdy lime on the App Store so check that out!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: