快速将使用MTLDevice初始化的自定义对象保存在本地

时间:2018-08-22 06:11:12

标签: swift swift4 metal metalkit

我只需要在本地保存一个自定义对象数组。我知道在Swift 4中,不需要NSCoding,因为可以使用一种称为“ codable”的新协议。但是,此时我更喜欢使用常规文件(使用NSKeyedUnarchiver)进行存档和取消存档。如果有替代品,我很想听听

我创建了绘图画布对象,其初始化方法包括MTLDevice。

   class Canvas: NSCoding {
        init( imageName : String , device : MTLDevice) {

           self.imageName = imageName
           self.device = device
        }

    // MARK: - Conform to NSCoding

        func encode(with aCoder: NSCoder) {

        aCoder.encode(imageName, forKey: "imageName ")
        aCoder.encode(device, forKey: "device ")

      }

      required  convenience init?(coder aDecoder: NSCoder) {

        guard let imageName = aDecoder.decodeObject(forKey: "imageName") as? String ,
              let device = aDecoder.decodeObject(forKey: "device") as? MTLDevice
        else {
                return nil
        }

        self.init(imageName: imageName , device:device)

      }

     // MARK: - Archivig & Unarchiving using a regular file (using NSKeyedUnarchiver)

       private class func getFileURL() -> NSURL {

        let documentsDirectory = FileManager().urls(for: (.documentDirectory), in: .userDomainMask).first!
        let archiveURL = documentsDirectory.appendingPathComponent("Canvas" )

        return archiveURL as NSURL

        }

       class func savePlayersToDisk(players: [Canvas]) {
        let success = NSKeyedArchiver.archiveRootObject(players, toFile: Canvas.getFileURL().path!)
        if !success {
            print("failed to save") // you could return the error here to the caller
        }
       }

       class func loadPlayersFromDisk() -> [Canvas]? {
        return NSKeyedUnarchiver.unarchiveObject(withFile: Canvas.getFileURL().path!) as? [Canvas]
       }

}

然后我尝试恢复画布对象,如下所示

let temporaryCanvasArray: [Canvas]  = [canvasScenes[0] ,canvasScenes[1]] // canvasScene is a array of Canvas Object

        Canvas.savePlayersToDisk(players: temporaryCanvasArray  )

                if let retreivedLayers = Canvas.loadPlayersFromDisk() {
                    print("loaded \(retreivedLayers.count) layers from disk")
                } else {
                    print("failed")
}

运行时,应用程序崩溃,并显示错误消息“ [MTLDebugDevice encodeWithCoder:]:无法识别的选择器已发送到实例0x102165a60”

毕竟我有一个问题。是否可以在本地使用MTLdevice保存画布对象? 如果是这样,我做错了什么?

0 个答案:

没有答案