问题
Can you show me the syntax or any sample programs to archive an NSArray of custom objects in Objective-C?
回答1:
Check out NSUserDefaults.
For Archiving your array, you can use the following code:
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:myArray] forKey:@"mySavedArray"];
And then for loading the custom objects in the array you can use this code:
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *savedArray = [currentDefaults objectForKey:@"mySavedArray"];
if (savedArray != nil)
{
NSArray *oldArray = [NSKeyedUnarchiver unarchiveObjectWithData:savedArray];
if (oldArray != nil) {
customObjectArray = [[NSMutableArray alloc] initWithArray:oldSavedArray];
} else {
customObjectArray = [[NSMutableArray alloc] init];
}
}
Make sure you check that the data returned from the user defaults is not nil
, because that may crash your app.
The other thing you will need to do is to make your custom object to comply to the NSCoder
protocol. You could do this using the -(void)encodeWithCoder:(NSCoder *)coder
and -(id)initWithCoder:(NSCoder *)coder
methods.
回答2:
If you want to save to a file (rather than using NSUserDefaults) you can use -initWithContentsOfFile:
to load, and -writeToFile:atomically:
to save, using NSArrays.
Example:
- (NSArray *)loadMyArray
{
NSArray *arr = [NSArray arrayWithContentsOfFile:
[NSString stringWithFormat:@"%@/myArrayFile", NSHomeDirectory()]];
return arr;
}
// returns success flag
- (BOOL)saveMyArray:(NSArray *)myArray
{
BOOL success = [myArray writeToFile:
[NSString stringWithFormat:@"%@/myArrayFile", NSHomeDirectory()]];
return success;
}
There's a lot of examples on various ways to do this here: http://www.cocoacast.com/?q=node/167
来源:https://stackoverflow.com/questions/3493156/how-to-archive-an-nsarray-of-custom-objects-to-file-in-objective-c