-1
在我的項目中,我需要保存一個具有UIImage,NSMutableArray和NSString對象的自定義對象(Person)。目前我能夠對NSString對象進行編碼和解碼,並將Person存檔到NSUserDefault中。除UIImage和NSArray外,一切正常。如何將自定義對象保存到包含UIImage和NSMutableArray的NSUserDefault?
-(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;
}
其實,保存UIImage不是我關心的問題。我想將自定義對象保存到NSUserDefault。事實上,我做到了。所有NSString屬性的行爲都如預期的那樣,但是當我取消存檔自定義對象時,我無法獲取圖像。 – Rokon