将 NSMutableArray 保存到 NSUserDefaults 的最佳方法是什么?
我有一个名为 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 中。我知道这是不可能的,所以我想知道哪种方法最简单?如果序列化是答案,那么如何实现呢?因为我阅读了文档,但无法完全理解它的工作方式。
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;
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该使用类似 NSKeyedArchiver 的方法将数组序列化为 NSData,将其保存到 NSUserDefaults,然后使用 NSKeyedUnarchiver > 稍后反序列化:
您需要在
Occasion
类中实现NSCoding
协议,并正确保存各种属性才能使其正常工作。有关详细信息,请参阅存档和序列化编程指南。执行此操作不应超过几行代码。像这样的东西:You should use something like
NSKeyedArchiver
to serialize the array to anNSData
, save it to theNSUserDefaults
and then useNSKeyedUnarchiver
to deserialize it later:You will need to implement the
NSCoding
protocol in yourOccasion
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:NSUserDefaults
用于用户首选项,而不是存储应用程序数据。使用 CoreData 或序列化对象进入文档目录。您需要让您的类实现NSCoding
协议才能正常工作。1) 在
Occasion.h
中实现NSCoding
2) 在
Occasion.m
中实现协议3) 将数据归档到文档目录中的文件
4 ) 取消存档...
NSUserDefaults
is intended for user preferences, not storing application data. Use CoreData or serialize the objects into the documents directory. You'll need to have your class implement theNSCoding
protocol for it to work.1) Implement
NSCoding
inOccasion.h
2) Implement the protocol in
Occasion.m
3) Archive the data to a file in documents directory
4) To unarchive...
您可以在
Occasion
中实现NSCoding
。然后,您使用 [NSKeyedArchiver archivedDataWithRootObject:myArray] 从数组创建一个
NSData
对象。您可以将其放入用户默认值中。You could implement
NSCoding
inOccasion
.You then use
[NSKeyedArchiver archivedDataWithRootObject:myArray]
to create anNSData
object from the array. You can put this into user defaults.