一个恰当的例子:这里的初学者请耐心等待。我刚刚学会了如何通过编码/解码&存档/解压来持久化对象。问题是我现在想要持久化一个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()
}
}有没有更好的方法呢?非常感谢。
发布于 2017-12-07 02:56:38
希望这能有所帮助
请添加正确的文件url来代替"filename“
func convertImageToDataAndWrite()
{
let img:UIImage = UIImage(named: "img1.png")!
let data:NSData? = UIImageJPEGRepresentation(img, 0.7)
if data != nil
{
var check:Bool = NSKeyedArchiver.archiveRootObject(data!, toFile: "filename")
}
}
func readImagefromFile()
{
let data:NSData = NSKeyedUnarchiver.unarchiveObjectWithFile("filename") as! NSData!
var img:UIImage = UIImage(data: data)!
}谢谢。
发布于 2017-12-07 03:17:07
我完全误解了NSCoding和存档的用法。“存档提供了一种将对象和值转换为独立于体系结构的字节流的方法,该字节流保留了对象和值的身份以及它们之间的关系。”
因此,要保存/加载UIImage:
// Define path
let documentsDirectory = FileManager.default.urls(for: .documentDirectory,in: .userDomainMask).first!
let photoURL = documentsDirectory.appendingPathComponent("photo.jpg")
// Convert selectedPhoto to Data and write to path
if let data = UIImageJPEGRepresentation(selectedPhoto, 1) {
try? data.write(to: photoURL)
}
// Load Data and init UIImage
UIImage(contentsOfFile: photoURL.path)https://stackoverflow.com/questions/47678272
复制相似问题