2016-07-31 64 views
-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; 
}  
+0

其實,保存UIImage不是我關心的問題。我想將自定義對象保存到NSUserDefault。事實上,我做到了。所有NSString屬性的行爲都如預期的那樣,但是當我取消存檔自定義對象時,我無法獲取圖像。 – Rokon

回答

0

您只能將某些類型的對象存儲到NSUserDefaults中,這些對象可以寫入到plist文件中。 (請看這裏https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/AboutPropertyLists/AboutPropertyLists.html) 所以你不能在那裏存儲圖像。你遇到數組問題的原因是集合(數組/字典)只有在兼容plist的對象時才兼容。最好的辦法是分別保存圖像/視頻文件,然後將URL(如String/NSString)寫入NSUserDefaults。最好的

相關問題