On viewDidLoad, my application populates the NSMutableArray arrayOfHaiku, which is an array of NSDictionary items, as follows:
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"haiku.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path])
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:@"haiku" ofType:@"plist"];
[fileManager copyItemAtPath:bundle toPath: path error:&error];
}
self.arrayOfHaiku = [[NSMutableArray alloc] initWithContentsOfFile: path];
While using the application, the user adds items to self.arrayOfHaiku. As of now I include the following code in viewDidUnload:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"haiku.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath: path])
{
[self.arrayOfHaiku writeToFile:path atomically:YES];
}
Here are my questions:
-
Does my code for
viewDidUnloada) simply write over the document storing the array in the Documents folder (that is, the array accessed inviewDidLoad) with the new, expanded array (which is what I want to do), or does it b) append the new, expanded array to the array already stored in the Documents folder so that I end up with an array that’s more than twice as long with a bunch of repeats? -
If the answer is “b)”, what do I need to change to do “a)”?
-
Is it better a) to do it the way I’m doing it, at
viewDidUnload, or b) to expand the array in the documents folder each time the user adds an item to self.arrayOfHaiku? -
If the answer is “b)”, what do I need to change to do “b)”?
Thanks for your help.
If the file exists, it will be overwritten, else it will be created (option a).
It all depends on the number of records. If you have a huge number then rewriting them everytime could be expensive. Otherwise you have to look to another solution. I honestly would not suggest using
viewDidUnloadbecause it might not fire in certain circumstances for example, if the app is backgrounded.Unfortunately, there is no ready function for ‘updating’ a plist with dictionary objects like
writeToFile:. You can use NSFileHandler’sfileHandleForUpdatingAtPath:function but then you would have to change the plist file manually (Which i dont think is a simple process).I personally would suggest using Core Data unless your data structure is very simple and ‘option a’ would not be an expensive process.
hope this helps.