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”]; //3NSFileManager *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 :).
Perfect! Simple and to the point. Just what I needed. Thanks.
By: Thomas S. Nielsen on March 18, 2010
at 7:48 am
Awesome,
I wish every blogger would ‘cut the crap’ and get to the point, like you do.
good job.
By: Yohann T. on June 26, 2010
at 10:42 am
Like you said at beginning, other blogs fail to show the whole deal. You really helped me with this today, thanks!
By: Simo Savonen on June 29, 2010
at 2:30 pm
Thank you! very usefull code. regards.
By: toto on July 27, 2010
at 8:01 pm
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,
By: A Arimi on August 17, 2010
at 5:23 am
Very, very helpful! It’s amazing how difficult this information was to find. Thank you so much for your post!
By: Pablo Kang on September 10, 2010
at 11:35 pm
Thanks!
Very Helpfull post!
By: Joel on September 14, 2010
at 6:04 pm
OH! Thanks you very much!!
It helps me alot !! :]
Tak
By: Tak on September 30, 2010
at 3:35 am
Excellent, I’ve been searching for a tutorial that clearly explains this. Great Job.
By: Frank on October 13, 2010
at 5:33 am
[…] Write & Read data to .plist (link) […]
By: Data Storage Alternatives on iOS (in a Nutshell) | dogan kaya berktas on October 16, 2010
at 8:27 pm
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
By: Iain Munro on November 8, 2010
at 11:01 pm
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 🙂
By: Anam Jawaid on November 11, 2010
at 9:41 am
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:
By: Mauricio Junior on November 12, 2010
at 9:54 pm
I’d like make with string … this example make with int… How should I do?
By: Mauricio Junior on November 12, 2010
at 10:15 pm
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?
By: Joe on November 22, 2010
at 8:10 pm
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.
By: Admin on November 22, 2010
at 10:30 pm
Brilliant, thanks so much!
Makes perfect sense now 🙂
By: Joe on November 22, 2010
at 11:49 pm
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
By: Peter on November 23, 2010
at 8:02 am
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 🙂
By: Admin on November 23, 2010
at 12:47 pm
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
By: Peter on November 23, 2010
at 9:31 pm
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
By: mohammed rafiq on November 30, 2010
at 11:57 am
Thanks very much.. exactly looking for this from long time
By: Kris on December 28, 2010
at 7:12 am
Thank you! helped me sooo much!
Thanks dude.
By: Paul on January 6, 2011
at 1:36 pm
Thank you so much!!!!!! Helped me a lot!!!! I can’t believe it!!
By: Ruben on January 12, 2011
at 10:02 am
This is cool! You should do a post on how to display this data in a UITableView.
By: Tate on February 12, 2011
at 7:07 pm
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?
By: Samer on February 17, 2011
at 2:02 pm
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.
By: Vijay Patel on February 26, 2011
at 2:48 pm
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
By: Paul Portman on March 2, 2011
at 9:57 pm
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.
By: Michael Daniels on March 5, 2011
at 11:07 pm
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. 🙂
By: Michael Daniels on March 5, 2011
at 11:10 pm
i used this code segment and got the output fine in simulator but in device SIGABRT error occurs. can anyone help me?
By: jamil on March 6, 2011
at 7:41 am
works perfect in device too.
Thanks
By: Devarajan on March 8, 2011
at 4:06 am
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
By: raj on April 15, 2011
at 6:39 am
@jamil bro i modified the line number 6 as i posted then there is no SIGABRT error
try it ….
By: raj on April 15, 2011
at 6:42 am
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
By: raj pardeshi on April 15, 2011
at 6:58 am
@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
By: Rahul on April 15, 2011
at 12:02 pm
of course yes, i have tried and the code is ok
By: gokben on March 5, 2015
at 1:22 pm
Great Post! i’ll tweet this post, very helpful keep up the good work and thank you once more! 😀
By: Jorge on May 17, 2011
at 3:33 am
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.
By: Mike T on May 28, 2011
at 11:46 pm
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
By: ghouse on June 16, 2011
at 5:59 am
Thanks! That really helps.
By: murat hacioglu on June 22, 2011
at 1:01 pm
Thanks a lot!! It is very useful
By: Russell on June 23, 2011
at 7:36 pm
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
By: aisya.aisya on July 14, 2011
at 5:03 am
Hey. This is great, I’ve been looking for a simple tut on how to do this.
Very good work, mate 🙂
By: Mikethepike on July 15, 2011
at 7:17 pm
Bundle of thanx
By: Junaid Akram on September 6, 2011
at 7:01 am
Good code
Regards
By: adel on September 7, 2011
at 5:24 pm
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?
By: Clarence Leong (@leongyewkwong) on September 8, 2011
at 7:22 am
i will try to write data into plist but old data was loose and only one record is inserted.
By: sudheer on September 12, 2011
at 11:44 am
AWESOME !!!
This is simple and perfect answer : )
By: 賴昭廷 on September 21, 2011
at 9:27 am
cheers !! just what i needed and works like a charm
By: Reuben on September 28, 2011
at 7:37 pm
How about a mod to show how to write a binary pList ?
By: mindeater123 on October 12, 2011
at 11:01 pm
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
By: Miha on October 18, 2011
at 7:51 am
hi i used ur code but my plist contain all garbage data with my data . will u plz give me suggestion to my query
By: sachin on October 19, 2011
at 5:36 pm
Thanks you very much!!!!!!
By: i.mobile on November 1, 2011
at 4:55 am
thanks for the tutorial
quick- simple and yet solves the problem…
just like the way I like the code to be. 🙂
By: Noman on December 13, 2011
at 9:42 am
omg… I spend week just for this complete and simple tutorial,even come with explanation.thank you.
i hope this work with imageNamed.
By: Albert on December 14, 2011
at 11:35 am
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.
By: GT on January 13, 2012
at 3:16 pm
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.
By: MuchAppreciated on January 20, 2012
at 8:01 pm
Thanks dear for giving the complete code….
By: anilkumar on February 10, 2012
at 1:12 pm
No other tutorial offered this solution….Thanks for the detail description…
By: venki on February 22, 2012
at 2:24 am
Thanks! That really help full
By: prasad on March 10, 2012
at 3:11 pm
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!
By: brando on March 29, 2012
at 2:03 pm
Thanks..!
By: asd on April 12, 2012
at 9:44 am
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 🙂
By: Gavin on April 30, 2012
at 7:20 am
thanks
By: waqas on May 17, 2012
at 9:54 am
Thanks man! Really helps!
By: Marcelo on May 19, 2012
at 4:18 pm
This was a great tutorial. Thanks!
By: Tom Dolan on May 22, 2012
at 8:03 pm
Very useful post, thank you !
By: Développeur mobile on June 7, 2012
at 9:12 am
thank you…
By: M N on June 13, 2012
at 1:23 am
Thanks. Much appreciated. Exactly what I was looking for.
By: Prasad on June 26, 2012
at 10:17 am
Awesome tutorial – straight to the point; Love it!
By: James B. on June 28, 2012
at 9:54 am
Very useful post, thank you
By: Anto on July 11, 2012
at 9:12 am
Thanks Mike T. I was wondering why the copy+pasta wasn’t working.
By: Big D on August 22, 2012
at 11:05 pm
Wow, It’s worked for me too.
Great tutorial and to the point.
Thanks & Good Luck Ahead
By: Raj on August 31, 2012
at 10:09 am
hey !! awesome tutorial !! did it in minutes !
thanks a lot !
By: shrawan zadoo on September 7, 2012
at 9:19 am
You saved my time lot. Thanks!..
One small question.
1. I couldn’t find myapp.plist file at my mainbundle resourcePath. Why?
By: prash on October 1, 2012
at 10:16 am
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
By: kiran on October 18, 2012
at 5:14 pm
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.
By: optimal stack on January 8, 2013
at 5:01 am
thanks alot
By: Omnia on March 31, 2013
at 8:59 pm
succinct and on the bull’s eye…good job
keep up the philanthropy mates….cheers
By: thorne on April 9, 2013
at 5:44 am
Thank you for this good post.
Helped me alot to load and store plist.
By: Torben on April 11, 2013
at 3:21 pm
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.
By: Wandy on April 21, 2013
at 12:45 pm
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.
By: online form creator on July 9, 2013
at 5:16 pm
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.
By: Online Forms on July 17, 2013
at 5:39 am
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.
By: online form generator on July 17, 2013
at 9:05 pm
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.
By: online forms on July 18, 2013
at 4:37 am
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.
By: online form builder on August 4, 2013
at 11:26 pm
Really Thanks..Very Helpful to me..
By: vijay on November 20, 2013
at 8:40 am
what about:
use 2 or more data plist: data1.plist, data2.plist, data3.plist
its posible in xCode?
ppVen
By: Pepe Ven on December 31, 2013
at 11:50 am
[…] https://ipgames.wordpress.com/tutorials/writeread-data-to-plist-file/ […]
By: Write/Read data to .plist file | iOS Code Snippets on January 18, 2014
at 8:52 pm
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!
By: organic protein powder on January 25, 2014
at 1:27 pm
Wow! That’s funny…
By: Nerdy Lime Apps on July 1, 2014
at 3:16 pm
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];
}
By: Kris on May 18, 2014
at 5:42 am
Thank you, great tutorial!
By: Rodrigo on May 29, 2014
at 9:30 pm
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!
By: Nerdy Lime Apps on July 1, 2014
at 3:14 pm
Hey I’m gabbar
By: Marwan.z on May 11, 2015
at 6:52 pm
Absolutely Perfect…
Thanks..
By: Akhil Karonnon on June 19, 2015
at 5:28 am
thank u so much..it is very useful for me….
By: praveena on September 4, 2015
at 12:06 pm
What version of Xcode did you use??
By: Rod on November 11, 2015
at 9:47 am
The codes has an error:
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
}
By: Rod on November 11, 2015
at 9:49 am
Superb. Simple and helpful.
By: Nikhil Pande on March 16, 2016
at 7:35 am
Check out the swift version here: http://rebeloper.com/read-write-plist-file-swift/ Step by step guide with images.
By: Sandor Nagy on May 31, 2016
at 4:34 pm