我正在使用 Core Data 进行持久存储,我收到下面列出的错误。我查看了这条消息,我知道这与我使用可转换类和自定义类有关。尽管我进行了研究,但我不确定如何解决它。我尝试遵守 NSSecureCoding 协议失败了。我发布我的原始代码是因为我认为从头开始尝试解决问题可能比尝试修复我在 NSSecureCoding 上的糟糕尝试更容易。先感谢您!任何帮助深表感谢。
'NSKeyedUnarchiveFromData' 不应用于取消归档,并将在未来版本中删除
我的自定义类:
public class SelectedImages: NSObject, NSCoding {
public var images: [SelectedImage] = []
enum Key: String {
case images = "images"
}
init(images: [SelectedImage]) {
self.images = images
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(images, forKey: Key.images.rawValue)
}
public required convenience init?(coder aDecoder: NSCoder) {
let mImages = aDecoder.decodeObject(forKey: Key.images.rawValue) as! [SelectedImage]
self.init(images: mImages)
}
}
public class SelectedImage: NSObject, NSCoding {
public var location: Int = 0
public var duration: Int = 10
public var localIdentifier: String = ""
enum Key: String {
case location = "location"
case duration = "duration"
case localIdentifier = "localIdentifier"
}
init(location: Int, duration: Int, localIdentifier: String) {
self.location = location
self.duration = duration
self.localIdentifier = localIdentifier
}
public override init() {
super.init()
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(location, forKey: Key.location.rawValue)
aCoder.encode(duration, forKey: Key.duration.rawValue)
aCoder.encode(localIdentifier, forKey: Key.localIdentifier.rawValue)
}
public required convenience init?(coder aDecoder: NSCoder) {
let mlocation = aDecoder.decodeInt32(forKey: Key.location.rawValue)
let mduration = aDecoder.decodeInt32(forKey: Key.duration.rawValue)
let mlocalIdentifier = aDecoder.decodeObject(forKey: Key.localIdentifier.rawValue) as! String
self.init(location: Int(mlocation), duration:Int(mduration), localIdentifier:String(mlocalIdentifier))
}
}
视图控制器:
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let userEntity = NSEntityDescription.entity(forEntityName: "EntityTest", in: managedContext)!
let selectedImages = NSManagedObject(entity: userEntity, insertInto: managedContext) as! EntityTest
let mImages = SelectedImages(images: selectionArrays)
selectedImages.setValue(mImages, forKeyPath: "image")
do {
try managedContext.save()
print("Images saved to core data")
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
let newViewController = PickerTest6()
self.navigationController?.pushViewController(newViewController, animated: true)