With just a few lines of code, you can read/write collections to/from files. The code below shows examples for writing and reading back both arrays and dictionaries.
Read and Write Collections to File
|
With just a few lines of code, you can read/write collections to/from files. The code below shows examples for writing and reading back both arrays and dictionaries.
|
http://ipgames.wordpress.com/tutorials/writeread-data-to-plist-file/
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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.
Read data:
1 2 3 4 5 6 7 8 9 |
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path]; //load from savedStock example int value int value; value = [[savedStock objectForKey:@"value"] intValue]; [savedStock release]; |
Write data:
1 2 3 4 5 6 7 8 9 10 11 |
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 really big data, sometimes it cannot be saved in this method, because the app takes too long to close and the system will terminate it immediately.