如何将自定义对象保存到包含UIImage和NSMutableArray的NSUserDefault?

时间:2016-07-31 03:37:09

标签: objective-c uiimage nsuserdefaults nscoding nskeyedarchiver

在我的项目中,我需要保存一个自定义对象(Person),它有一个UIImage,NSMutableArray和NSString对象。目前,我能够对NSString对象进行编码和解码,并将人员存档到NSUserDefault中。除了UIImage和NSArray之外,一切正常。

-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
  if (self = [super init]) {
    self.userName = [aDecoder decodeObjectForKey:@"userName"]; //NSString
    self.profileImage = [aDecoder decodeObjectForKey:@"profileImage"]; //UIImage
    self.uplodedVideoArray = [aDecoder decodeObjectForKey:@"uplodedVideoArray"]; //NSMutableArray
  }
 return self;
}

-(void)encodeWithCoder:(NSCoder *)aCoder
{
 [aCoder encodeObject:self.userName forKey:@"userName"]; //NSString
 [aCoder encodeObject:self.profileImage forKey:@"profileImage"]; //UIImage
 [aCoder encodeObject:self.uplodedVideoArray forKey:@"uplodedVideoArray"]; //NSMutableArray
}

-(void)archivePerson
{
 NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:[Person sharedInstance]];
 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
 [defaults setObject:encodedObject forKey:@"Person"];
 [defaults synchronize];
}

-(Person *)unarchivePerson
{
 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
 NSData *encodedObject = [defaults objectForKey:@"Person"];
 Person *person = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
 return person;
}    

1 个答案:

答案 0 :(得分:0)

您只能将某些类型的对象存储到NSUserDefaults,这些类型可以写入plist文件。 (见https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/AboutPropertyLists/AboutPropertyLists.html) 所以你不能在那里存储图像。您遇到数组问题的原因是,如果集合(数组/字典)仅包含plist兼容对象,则它们仅兼容plist。最好的方法是单独保存图像/视频文件,然后将URL(作为String / NSString)写入NSUserDefaults。最好