将NSMutableArray保存到NSUserDefaults的最佳方法是什么?

时间:2011-10-12 16:37:43

标签: iphone serialization nsmutablearray nsuserdefaults custom-object

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

#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。我知道这是不可能的,所以我想知道哪种方法最简单?如果序列化是答案,那么如何?因为我阅读了文档但却无法理解它的完整工作方式。

3 个答案:

答案 0 :(得分:11)

您应该使用类似NSKeyedArchiver的内容将数组序列化为NSData,将其保存到NSUserDefaults,然后再使用NSKeyedUnarchiver对其进行反序列化:

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

//...

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

您需要在NSCoding类中实现Occasion协议,并正确保存各种属性以使其正常工作。有关更多信息,请参阅Archives and Serializations Programming Guide。执行此操作不应超过几行代码。类似的东西:

- (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;
}

答案 1 :(得分:4)

NSUserDefaults用于用户首选项,而不是存储应用程序数据。使用CoreData或将对象序列化到文档目录中。您需要让您的类实现NSCoding协议才能生效。

1)在NSCoding

中实施Occasion.h
@interface Occasion : NSObject <NSCoding>

2)在Occasion.m

中实施协议
- (id)initWithCoder:(NSCoder *)aDecoder {

    if (self = [super init]) {

        self.title = [aDecoder decodeObjectForKey:@"title"];
        self.date = [aDecoder decodeObjectForKey:@"date"];
        self.imagePath = [aDecoder decodeObjectForKey:@"imagePath"];

    }            
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {

    [aCoder encodeObject:title forKey:@"title"];
    [aCoder encodeObject:date forKey:@"date"];
    [aCoder encodeObject:imagePath forKey:@"imagePath"];
}

3)将数据存档到文档目录中的文件

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                    NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *path= [documentsPath stringByAppendingPathComponent:@“occasions”];
[NSKeyedArchiver archiveRootObject:occasions toFile:path];

4)取消归档......

NSMutableArray *occasions = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

答案 2 :(得分:1)

您可以在NSCoding中实施Occasion

然后使用[NSKeyedArchiver archivedDataWithRootObject:myArray]从数组中创建NSData对象。您可以将其设置为用户默认值。