Leave a comment

Write and Read data to plist file

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.


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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: