Search code examples
iosimagedictionaryplist

Save images to NSMutableDictionary and than to plist


I need to save images which I get from server using

[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:URL]]];

To NSMutableDictionary - it's ok for me, I'm doing it like this (it is in loop for every fetched image):

[self.imagesDict setObject:image forKey:[[xmlArray objectAtIndex:x] objectForKey:@"_img"]];

And than, I need to save it to disc. There were two solutions for me, but no one works... :-(. First one was save it do NSUserDefaults and second is save it to .plist file to root of iPhone. I want to go with that .plist, so I did:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pathLD = [documentsDirectory stringByAppendingPathComponent:@"imagesDict"];

[self.imagesDict writeToFile:pathLD atomically:YES];

But when I try to NSLog it, it's not working. However when I save to dictionary some string instead of image, it works like a charm. So can someone help me please what I'm doing wrong? Thanks a lot!


Solution

  • You can not store the UIImage objects directly. Put their NSData inside the NSDictionary to be able to save them. Either the downloaded NSData or create it new via UIImagePNGRepresentation(image)

    From the Dokumentation of NSDictionary's writeToFile:atomically:

    This method recursively validates that all the contained objects are property list objects (instances of NSData, NSDate, NSNumber, NSString, NSArray, or NSDictionary) before writing out the file, and returns NO if all the objects are not property list objects, since the resultant file would not be a valid property list.