class func unarchiveFromFile(file : NSString) -> SKNode? {
let path = NSBundle.mainBundle().pathForResource(file as String, ofType: "sks")
var sceneData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe!, error: nil)
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene
archiver.finishDecoding()
return scene
所以我在var sceneData = NSData上得到一个错误:表达的类型含糊不清,有更多的上下文。我非常困难
答案 0 :(得分:0)
pathForResource
会返回一个可选项
dataWithContentsOfFile
期望非可选。
展开可选
let path = NSBundle.mainBundle().pathForResource(file as String, ofType: "sks")!
或执行可选绑定
if let path = NSBundle.mainBundle().pathForResource(file as String, ofType: "sks") {
// path is safe
}
实际上dataWithContentsOfFile
的正确语法是
let sceneData = NSData(contentsOfFile:path, options: .DataReadingMappedIfSafe, error: nil)
并且.DataReadingMappedIfSafe
永远不需要打开。
编辑:
完整代码:
class func unarchiveFromFile(file : NSString) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file as String, ofType: "sks") {
// path is safe
let sceneData = NSData(contentsOfFile:path, options: .DataReadingMappedIfSafe, error: nil)
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene
archiver.finishDecoding()
return scene
}
return nil
}