-1

In my project I need to save a custom object(Person) which have an UIImage, NSMutableArray and NSString objects. Currently I am able to encode and decode the NSString objects and archive Person to in NSUserDefault. Everything works fine except for UIImage and 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;
}    
Rokon
  • 326
  • 2
  • 10
  • Actually, saving UIImage is not my concern. I want to save a Custom Object to NSUserDefault. In fact I did it. All the NSString properties are behaving as expected but I can not get the image when I unarchive the Custom Object. – Rokon Jul 31 '16 at 18:07

1 Answers1

0

You can only store certain types of objects to NSUserDefaults, the same types that can be written to plist files. (See here https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/AboutPropertyLists/AboutPropertyLists.html ) So you cannot store an image there. The reason you're having problems with the array is that collections (arrays/dictionaries) are only plist compatible if they contain plist compatible objects only. Your best approach is to save your image/video files seperately and then write the URL (as String/NSString) to NSUserDefaults. Best

Jef
  • 4,662
  • 2
  • 23
  • 32