如何将自定义对象的NSArray归档到Objective-C中的文件 [英] How to archive an NSArray of custom objects to file in Objective-C

查看:89
本文介绍了如何将自定义对象的NSArray归档到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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆