【问题标题】:iPhone - User Defaults and UIImagesiPhone - 用户默认值和 UIImages
【发布时间】:2023-03-12 23:25:01
【问题描述】:

过去几个月我一直在开发 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 不允许我做的事情。想法?我觉得我可能走错了路……

【问题讨论】:

  • Ben 的回答是正确的,但您认为需要知道文件类型的假设不正确。 UIImagePNGRepresentation 将 NSData 作为 PNG 文件返回,无论它在加载时采用什么格式。

标签: iphone cocoa-touch uiimage nsuserdefaults


【解决方案1】:

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

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

NSString   *filename = myImageFilename;
[UIImagePNGRepresentation(image) writeToFile: myImageFilename atomically];
[[NSUserDefaults standardDefaults] setObject: myImageFilename forKey: @"lastImageFilename"]; 

【讨论】:

  • 知道了。跟进问题。磁盘上的内存是如何管理的?有没有对应的“removeFromFile”类型方法?
  • 看看 NSFileManager。有一个 -removeItemAtPath:error: 方法可以做你想做的事。
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多