views:

285

answers:

1

Hello,

I've been developing an iPhone app for the last few months. Recently I wanted to up performance and cache a few of the images that are used in the UI. The images are downloaded randomly from the web by the user so I can't add specific images to the project. I'm also already using NSUserDefaults to save other info within the app.

So now I'm attempting to save a dictionary of UIImages to my NSUserDefaults object and get...

-[UIImage encodeWithCoder:]: unrecognized selector sent to instance

I then decided to subclass UIImage with a class named UISaveableImage and implement NSCoding. So now I'm at...

@implementation UISaveableImage

-(void)encodeWithCoder:(NSCoder *)encoder
{
   [encoder encodeObject:super forKey:@"image"];
}

-(id)initWithCoder:(NSCoder *)decoder
{
    if (self=[super init]){
        super =  [decoder decodeObjectForKey:@"image"];
    }
    return self;
}

@end

which isn't any better than where I started. If I was able to convert an UIImage to NSData I would be good, but all I can find are function like UIImagePNGRepresentation which require me to know what type of image this was. Something that UIImage doesn't allow me to do. Thoughts? I feel like I might have wandered down the wrong path...

+1  A: 

You don't want to store images in NSUserDefaults. They're big blobs of data, and NSUserDefaults is stored as a plist; you want to write small bits of info to it.

You should write the images to disk, and then store the filenames to defaults:

NSString   *filename = myImageFilename;
[UIImagePNGRepresentation(image) writeToFile: myImageFilename atomically];
[[NSUserDefaults standardDefaults] setObject: myImageFilename forKey: @"lastImageFilename"]; 
Ben Gottlieb
Got it. Follow up question. How is memory managed on the disk? Is there a corresponding "removeFromFile" type method?
Staros
Take a look at NSFileManager. There's a -removeItemAtPath:error: method there that will do what you want.
Ben Gottlieb