包含var sceneData代码的行给出了一个错误,显然是因为" path"串。有谁知道如何解决这个问题?谢谢!
extension SKNode {
class func unarchiveFromFile(_ file : String) -> SKNode? {
if let path = Bundle.main.path(forResource: file, ofType: "sks") {
var sceneData = Data(bytesNoCopy: path, count: .DataReadingMappedIfSafe, deallocator: nil)!
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene
archiver.finishDecoding()
return scene
} else {
return nil
}
}
}
答案 0 :(得分:8)
Data(bytesNoCopy:
需要指针而不是字符串路径。
从磁盘读取Data
的API为Data(contentsOf
,但是需要一个网址
extension SKNode {
class func unarchiveFromFile(_ file : String) -> SKNode? {
if let url = Bundle.main.url(forResource: file, withExtension: "sks") {
do {
var sceneData = try Data(contentsOf: url)
var archiver = NSKeyedUnarchiver(forReadingWith: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene
archiver.finishDecoding()
return scene
} catch {
return nil
}
} else {
return nil
}
}
}
在Swift 3中,我将方法重命名为
class func unarchive(from file : String) -> SKNode? { ...