iPhone - 用户默认值和UIImages [英] iPhone - User Defaults and UIImages

查看:113
本文介绍了iPhone - 用户默认值和UIImages的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去几个月我一直在开发一个iPhone应用程序。最近我想提高性能和缓存一些在UI中使用的图像。用户从网站随机下载图像,因此我无法向项目中添加特定图像。我也已经使用NSUserDefaults保存应用程序内的其他信息。

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.

现在我试图保存UIImages的字典到我的NSUserDefaults对象,并获得.. 。

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

- [UIImage encodeWithCoder:]:无法识别的选择器发送到实例

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

然后我决定将UIImage一个名为UISaveableImage的类,并实现NSCoding。现在我在...

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

比我开始的地方。如果我能够将UIImage转换为NSData我会很好,但我可以找到的是像UIImagePNGRepresentation这样的函数,需要我知道这是什么类型的图像。 UIImage不允许我做的事情。想法?我觉得我可能已经走错了错误的路径...

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...

推荐答案

您不想将图像存储在NSUserDefaults。它们是大数据块,NSUserDefaults存储为plist;

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

这篇关于iPhone - 用户默认值和UIImages的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆