Have a question about saving to plist
I have a .plist filled with data that ships with my app.
It's basically an array of dictionaries with other arrays/dictionaries in it.
The values I take from this array a开发者_高级运维nd use in my app may be a name, so "Computer".
I'm adding a feature to let the user create their own item, instead of choosing from what is loading from the array. But should I then save this item into the same .plist, or create a separate .plist for each user?
Then, how do I pull info from both the standard .plist and the user created .plist and load them into one tableView?
If you're writing for iOS, you can't really save to same plist file because you can't write to the application bundle.
One thing you could do is save a copy of that plist to the application's Documents folder, and then modify that same plist, that way all your data is unified in a single file.
Or you can always load the original plist from the application bundle, make a mutable copy of the NSArray
, load an additional plist from the Documents folder with the user's objects, and append them to the NSMutableArray
by calling addObjectsFromArray
.
Or you can even keep them in separate NSArray
but display them in the table view as one by returning [originalDataArray count] + [userDataArray count]
from the tableView:numberOfRowsInSection:
method of your table view data source, and of course use the appropriate data in the tableView:cellForRowAtIndexPath:
method.
EDIT:
About saving the user data, you don't necessarily have to worry about writing a plist.
The NSArray
conforms to the NSCoding
protocol, and so do NSDictionary
, which means you can easily save it and load it using something like the NSKeyedArchiver
class.
Here's an example of something I had in an old project of mine, where I had a NSMutableArray
that held some user generated data, and I saved it and loaded it with NSKeyedArchiver
(simplified to only show the relevant code, and was done over a year ago when I was just starting with ios, so might not be the best possible way of doing it):
- (BOOL) saveData
{
BOOL success = NO;
NSArray *pathList = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, NO);
NSString *path = [[[pathList objectAtIndex:0] stringByAppendingPathComponent:@"data.txt"] stringByExpandingTildeInPath];
success = [NSKeyedArchiver archiveRootObject:myArray toFile:path];
//note: myArray is an NSMutableArray, could be an NSArray
return success;
}
- (BOOL) loadData
{
BOOL success = NO;
NSArray *pathList = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, NO);
NSString *path = [[[pathList objectAtIndex:0] stringByAppendingPathComponent:@"data.txt"] stringByExpandingTildeInPath];
if( (myArray = [NSKeyedUnarchiver unarchiveObjectWithFile:path]) )
{
[myArray retain];
success = YES;
}
else
{
myArray = [[NSMutableArray alloc] init];
success = NO;
}
return success;
}
精彩评论