gpt4 book ai didi

swift - 如何在 Swift 和 Xcode 中保存对象数组(带有图像变量)?

转载 作者:行者123 更新时间:2023-11-28 13:51:55 25 4
gpt4 key购买 nike

我想知道如何保存来自以下类的对象数组:

class CustomDocument: NSObject, NSCoding {
let name : String
let image : UIImage

init(n: String, i: UIImage){
name = n
image = i
}

//other code excluded
}

最初,我将这个数组保存到 User Defaults。由于对象占用了大量空间,因此导致应用程序出现大量延迟。

保存占用大量空间的数据数组的最佳方法是什么?

非常感谢您的帮助,感谢所有回复。

最佳答案

试试这段代码,希望对你有帮助:

class CustomDocument: NSObject, NSCoding  {

var name : String?
var image : UIImage?

func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "namekey")
if let imageData = image!.jpegData(compressionQuality: 1.0){
aCoder.encode(imageData, forKey: "imagekey")
}
UserDefaults.standard.synchronize()
}

required convenience init?(coder aDecoder: NSCoder) {
self.init()
if let name = (aDecoder.decodeObject(forKey: "namekey") as? String){
self.name = name
}
if let imageData = (aDecoder.decodeObject(forKey: "imagekey") as? Data){
if let image = UIImage(data: imageData){
self.image = image
}
}
}
}


func archiveDocument(document:CustomDocument) -> Data? {
do {
let archivedObject = try NSKeyedArchiver.archivedData(withRootObject: document, requiringSecureCoding: false)
return archivedObject

} catch {
// do something with the error
}
return nil
}


func unarchiveDocument(unarchivedObject:Data) -> CustomDocument? {
do {
if let document = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(unarchivedObject) as? CustomDocument {
return document
}
} catch {
// do something with the error
}
return nil
}

例子:

//Set the object, also you can use an array instead of an object
let obj = CustomDocument()
obj.name = "doc1"
obj.image = UIImage(named: "my_image")
if let archivedObject = archiveDocument(document: obj){
UserDefaults.standard.set(archivedObject, forKey: "obj")
}

//Get the object
if let archivedObject = UserDefaults.standard.data(forKey: "obj"){
obj = unarchiveDocument(unarchivedObject: archivedObject)
let myImage = obj?.image
}

关于swift - 如何在 Swift 和 Xcode 中保存对象数组(带有图像变量)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54489922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com