iPhone - User Defaults and UIImages

时光怂恿深爱的人放手 提交于 2019-12-08 02:45:04

问题


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:


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"]; 



回答2:


Stumbling upon this a year later. I would add (in case someone else stumbles here as well) that you should store the images in the cache directory and avoid iTunes trying to back them up.

- (NSString *)pathForSearchPath:(NSSearchPathDirectory)searchPath {
  NSArray *paths = NSSearchPathForDirectoriesInDomains(searchPath, NSUserDomainMask, YES);
  NSString *directoryPath = [paths objectAtIndex:0];
  return directoryPath;
}

- (NSString *)cacheDirectoryPath {
  return [self pathForSearchPath:NSCachesDirectory];
}


来源:https://stackoverflow.com/questions/2625215/iphone-user-defaults-and-uiimages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!