2

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

所以现在我正在尝试将 UIImages 字典保存到我的 NSUserDefaults 对象并获取...

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

然后我决定用一个名为 UISaveableImage 的类继承 UIImage 并实现 NSCoding。所以现在我在...

@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 不允许我做的事情。想法?我觉得我可能走错了路……

4

2 回答 2

6

您不想将图像存储在 NSUserDefaults 中。它们是大块数据,NSUserDefaults 存储为 plist;您想向其写入少量信息。

您应该将图像写入磁盘,然后将文件名存储为默认值:

NSString   *filename = myImageFilename;
[UIImagePNGRepresentation(image) writeToFile: myImageFilename atomically];
[[NSUserDefaults standardDefaults] setObject: myImageFilename forKey: @"lastImageFilename"]; 
于 2010-04-12T20:40:26.033 回答
1

一年后偶然发现了这一点。我会补充(以防其他人也在这里绊倒)您应该将图像存储在缓存目录中,并避免 iTunes 尝试备份它们。

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

- (NSString *)cacheDirectoryPath {
  return [self pathForSearchPath:NSCachesDirectory];
}
于 2011-07-07T01:11:36.430 回答