I’ve read a lot about archiving a single array with NSKeyedArchiver. But how would I save two arrays?
I need to store/retrieve data for two view controllers within a UITabBarController. Each of the two view controllers create objects of the same custom class, but store them in a separate array for each view controller.
My current code uses a separate method for saving each array. The problem is that when archiving the second array, it overrides the first one. I can’t get them both to save. I think I either need to save the two arrays to their own file or combine the data into a single file. I’m just not sure how to write the code for this. Can anyone help??
- (void)saveFermentableIngredients
{
NSMutableData *fermentableData = [[NSMutableData alloc] init];
NSKeyedArchiver *fermentableArchiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:fermentableData];
[fermentableArchiver encodeObject:self.fermentableIngredients forKey:@"FermentableIngredients"];
[fermentableArchiver finishEncoding];
[fermentableData writeToFile:[self dataFilePath] atomically:YES];
}
- (void)saveHopIngredients
{
NSMutableData *hopData = [[NSMutableData alloc] init];
NSKeyedArchiver *hopArchiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:hopData];
[hopArchiver encodeObject:self.hopIngredients forKey:@"HopIngredients"];
[hopArchiver finishEncoding];
[hopData writeToFile:[self dataFilePath] atomically:YES];
}
I should mention that I’ve done the usual setup here with implementing the initWithCoder and encodeWithCoder methods. I suspect the problem is really in the code I posted above.
I ended up saving each array to a separate file. First I declared the two separate file paths like this:
Then I referenced each file path in the save methods I put in my original question. So in the first method I would have written my writeToFile method like this: