如何将自定义对象的NSArray归档到Objective-C中的文件 [英] How to archive an NSArray of custom objects to file in Objective-C
问题描述
您能告诉我在Objective-C中归档自定义对象的NSArray的语法或任何示例程序吗?
Can you show me the syntax or any sample programs to archive an NSArray of custom objects in Objective-C?
推荐答案
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];
}
}
请确保您检查从用户默认值返回的数据不是nil
,因为这可能会使您的应用程序崩溃.
Make sure you check that the data returned from the user defaults is not nil
, because that may crash your app.
您需要做的另一件事是使您的自定义对象符合NSCoder
协议.您可以使用-(void)encodeWithCoder:(NSCoder *)coder
和-(id)initWithCoder:(NSCoder *)coder
方法.
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.
这篇关于如何将自定义对象的NSArray归档到Objective-C中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!