【发布时间】:2017-12-06 15:47:41
【问题描述】:
例子:这里的初学者请多多包涵。我刚刚学会了如何通过编码/解码和归档/取消归档来持久化对象。问题是现在我想保留一个 UIImage。推荐的方法是什么?
我当前的实现可行但看起来很奇怪:
class Photo: NSObject, NSCoding {
static let documentsDirectory = FileManager.default.urls(for: .documentDirectory,in: .userDomainMask).first!
static let archiveURL = documentsDirectory.appendingPathComponent("photo")
static func saveToDisk(selectedPhoto: UIImage) {
NSKeyedArchiver.archiveRootObject(selectedPhoto, toFile: archiveURL.path)
}
static func loadFromDisk() -> UIImage? {
guard let unarchivedPhoto = NSKeyedUnarchiver.unarchiveObject(withFile: archiveURL.path) as? UIImage
else {return nil}
return unarchivedPhoto
}
func encode(with aCoder: NSCoder) {
}
convenience required init?(coder aDecoder: NSCoder) {
self.init()
}
}
有更好的方法吗?非常感谢。
【问题讨论】:
-
您希望如何将 plist 文件转换为 UIImage?如果您真的想将 UIImage 保存到 plist 文件中(您不应该),您首先需要将 UIImage 转换为 JPEG 或 PNG 数据表示。
-
ARRH 我现在看到了。所以我应该使用 UIImageJPEGRepresentation() 将其转换然后写入路径,对吗?抱歉,我知道这是一个菜鸟问题。
-
是的,您需要将其保存为 JPEG 或 PNG。我建议使用 JPEG,因为 PNG 会丢弃图像方向
-
非常感谢 Leo,现在我明白了!干杯!天哪,我太笨了。
-
我回滚了你上次的编辑。不要使用解决方案编辑您的问题,而是在下面发布您的解决方案作为实际答案。