在iOS中保存/序列化自定义对象的正确方法

我有一个自定义对象,一个UIImageView子类有几个gestureRecognizer对象。

如果我有一些这些对象存储在一个NSMutableArray ,这个对象数组将如何保存到磁盘,以便可以在用户再次运行应用程序时加载它?

我想从磁盘加载数组,并使用对象。

我的类似的实现是以下,完美的作品:

自定义对象(设置)应该实现协议NSCoding:

 -(void)encodeWithCoder:(NSCoder *)encoder{ [encoder encodeObject:self.difficulty forKey:@"difficulty"]; [encoder encodeObject:self.language forKey:@"language"]; [encoder encodeObject:self.category forKey:@"category"]; [encoder encodeObject:self.playerType forKey:@"playerType"]; } - (id)initWithCoder:(NSCoder *)decoder { if (self = [super init]) { self.difficulty = [decoder decodeObjectForKey:@"difficulty"]; self.language = [decoder decodeObjectForKey:@"language"]; self.category = [decoder decodeObjectForKey:@"category"]; self.playerType = [decoder decodeObjectForKey:@"playerType"]; } return self; } 

下面的代码将自定义对象写入一个文件(set.txt),然后将其恢复到数组myArray:

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"set.txt"]; NSMutableArray *myObject=[NSMutableArray array]; [myObject addObject:self.settings]; [NSKeyedArchiver archiveRootObject:myObject toFile:appFile]; NSMutableArray* myArray = [NSKeyedUnarchiver unarchiveObjectWithFile:appFile]; 
 //store the array [NSKeyedArchiver archiveRootObject:myArray toFile:@"someFile"]; //load the array NSMutableArray* myArray = [NSKeyedUnarchiver unarchiveObjectWithFile:@"someFile"]; 

官方参考 。

请注意,当数组包含自定义对象types时,必须确保types符合NSCoding协议,然后才能工作。

本博客文章解释了如何使用NSKeyedArchiver将自定义对象数组存储到磁盘,并使用NSKeyedUnarchiver读取它:

http://www.cocoabuilder.com/archive/cocoa/240775-saving-nsarray-of-custom-objects.html

苹果在这个问题上也有一个非常有用的指南,即档案和序列化编程指南 。

如果有人需要,我想分享我对Kostas解决scheme的改进。

  1. 类名可以用来生成文本文件名来存储对象。
  2. 在viewWillDisappear方法中保存视图控制器的对象并将其恢复到viewDidLoad方法是一个很好的解决scheme。
  3. 文件名应该在单独的方法中生成以避免重复的代码。
  4. 恢复对象之后,应该检查是不是零。

 - (void)viewDidLoad { [super viewDidLoad]; // Restoring form object from the file NSString *formFilePath = [self formFilePath]; RRCreateResumeForm *form = [NSKeyedUnarchiver unarchiveObjectWithFile:formFilePath]; if (form != nil) { self.formController.form = form; } } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; // Saving the form object to the file NSString *formFilePath = [self formFilePath]; [NSKeyedArchiver archiveRootObject:self.formController.form toFile:formFilePath]; } // Returns a file path to the file with stored form data for form controller - (NSString *)formFilePath { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *formClassName = NSStringFromClass( [self.formController.form class] ); NSString *formFileName = [NSString stringWithFormat:@"%@.txt", formClassName]; NSString *formFilePath = [documentsDirectory stringByAppendingPathComponent:formFileName]; return formFilePath; }