将NSMutableArray保存到NSUserDefaults的最佳方法是什么? [英] What is the best way to save an NSMutableArray to NSUserDefaults?

查看:118
本文介绍了将NSMutableArray保存到NSUserDefaults的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Occasion的自定义对象,定义如下:

I have a custom object called Occasion defined as follows:

#import <Foundation/Foundation.h>


@interface Occasion : NSObject {

NSString *_title;
NSDate *_date;
NSString *_imagePath;    

}

@property (nonatomic, retain) NSString *title;
@property (nonatomic, retain) NSDate *date;
@property (nonatomic, retain) NSString *imagePath;

现在我有一个NSMutableArray of Occasions,我想保存到NSUserDefaults。我知道这是不可能的,所以我想知道哪种方法最简单?如果序列化是答案,那么如何?因为我阅读了文档,但无法理解它完全有效的方式。

Now I have an NSMutableArray of Occasions which I want to save to NSUserDefaults. I know it's not possible in a straight forward fashion so I'm wondering which is the easiest way to do that? If serialization is the answer, then how? Because I read the docs but couldn't understand the way it works fully.

推荐答案

你应该使用类似<$ c $的东西C>的NSKeyedArchiver 序列化阵列的 NSData的,将其保存到 NSUserDefaults的和然后使用 NSKeyedUnarchiver 稍后反序列化:

You should use something like NSKeyedArchiver to serialize the array to an NSData, save it to the NSUserDefaults and then use NSKeyedUnarchiver to deserialize it later:

NSData *serialized = [NSKeyedArchiver archivedDataWithRootObject:myArray];
[[NSUserDefaults standardUserDefaults] setObject:serialized forKey:@"myKey"];

//...

NSData *serialized = [[NSUserDefaults standardUserDefaults] objectForKey:@"myKey"];
NSArray *myArray = [NSKeyedUnarchiver unarchiveObjectWithData:serialized];

您需要实施 NSCoding 协议在 Occasion 类中,并正确保存各种属性以使其正常工作。欲了解更多信息,请参阅归档和序列化编程指南。执行此操作不应超过几行代码。是这样的:

You will need to implement the NSCoding protocol in your Occasion class and correctly save the various properties to make this work correctly. For more information see the Archives and Serializations Programming Guide. It shouldn't be more than a few lines of code to do this. Something like:

- (void)encodeWithCoder:(NSCoder *)coder {
    [super encodeWithCoder:coder];

    [coder encodeObject:_title forKey:@"_title"];
    [coder encodeObject:_date forKey:@"_date"];
    [coder encodeObject:_imagePath forKey:@"_imagePath"];
}

- (id)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];

    _title = [[coder decodeObjectForKey:@"_title"] retain];
    _date = [[coder decodeObjectForKey:@"_date"] retain];
    _imagePath = [[coder decodeObjectForKey:@"_imagePath"] retain];

    return self;
}

这篇关于将NSMutableArray保存到NSUserDefaults的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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