Correct way to save/serialize custom objects in iOS

后端 未结 4 1924
北海茫月
北海茫月 2020-11-29 18:29

I have a custom object, a UIImageView subclass which has a few gestureRecognizer objects.

If I have a number of these objects stored in a

4条回答
  •  -上瘾入骨i
    2020-11-29 18:56

    I would like to share my improvements to Kostas solution, if somebody needs them.

    1. A class name can be used to generate text file name to store object.
    2. It is a good solution to save objects of a view controller in viewWillDisappear method and restore them in viewDidLoad method.
    3. File name should be generated in separate method to avoid duplicate code.
    4. After restoring object, it should be checked to be not nil.

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

提交回复
热议问题