我想知道如何保存以下类中的对象数组:
class CustomDocument: NSObject, NSCoding {
let name : String
let image : UIImage
init(n: String, i: UIImage){
name = n
image = i
}
//other code excluded
}
最初,我将此数组保存为“用户默认设置”。由于对象占用了大量空间,因此在应用程序中造成了很多滞后。
保存占用大量空间的数据数组的最佳方法是什么?
非常感谢您的帮助,感谢您的答复。
答案 0 :(得分:0)
尝试以下代码,希望对您有所帮助:
<div style="">
<div style="outline: none;">
<input class="item" type="checkbox" style="outline: none; margin-left: 0px; margin-right: 6px;" id="InsertRecordCheckList_3a4dfdb26cc834_checked_0">
<label for="InsertRecordCheckList_3a4dfdb26cc834_checked_0">Apple</label>
</div>
<div style="outline: none;">
<input class="item" type="checkbox" style="outline: none; margin-left: 0px; margin-right: 6px;" id="InsertRecordCheckList_3a4dfdb26cc834_checked_1">
<label for="InsertRecordCheckList_3a4dfdb26cc834_checked_1">Banana</label>
</div>
<div style="outline: none;">
<input class="item" type="checkbox" style="outline: none; margin-left: 0px; margin-right: 6px;" id="InsertRecordCheckList_3a4dfdb26cc834_checked_2">
<label for="InsertRecordCheckList_3a4dfdb26cc834_checked_2">Melon</label>
</div>
<div style="outline: none;">
<input class="item" type="checkbox" style="outline: none; margin-left: 0px; margin-right: 6px;" id="InsertRecordCheckList_3a4dfdb26cc834_checked_3">
<label for="InsertRecordCheckList_3a4dfdb26cc834_checked_3">Mango</label>
</div>
<div style="outline: none;">
<input class="item" type="checkbox" style="outline: none; margin-left: 0px; margin-right: 6px;" id="InsertRecordCheckList_3a4dfdb26cc834_checked_4">
<label for="InsertRecordCheckList_3a4dfdb26cc834_checked_4">Grapes</label>
</div>
<div style="outline: none;">
<input class="item" type="checkbox" style="outline: none; margin-left: 0px; margin-right: 6px;" id="InsertRecordCheckList_3a4dfdb26cc834_checked_5">
<label for="InsertRecordCheckList_3a4dfdb26cc834_checked_5">Peach</label>
</div>
</div>
示例:
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
}