我有一个名为 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 中。我知道这是不可能的,所以我想知道哪种方法最简单?如果序列化是答案,那么如何实现呢?因为我阅读了文档但无法完全理解它的工作方式。
你应该使用类似的东西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
类并正确保存各种属性以使其正常工作。欲了解更多信息,请参阅档案和序列化编程指南 http://developer.apple.com/library/ios/#DOCUMENTATION/Cocoa/Conceptual/Archiving/Archiving.html。执行此操作不应超过几行代码。就像是:
- (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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)