这部分代码已过时,它会出错和错误。
通话可以抛出,但没有标记为'尝试'并且没有处理错误
extension SKNode {
class func unarchiveFromFile(file : String) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
let sceneData = NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMapped)
let archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene
archiver.finishDecoding()
return scene
} else {
return nil
}
}
}
我的第一个代码是:
extension SKNode {
class func unarchiveFromFile(file : String) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
var 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
} else {
return nil
}
}
}
答案 0 :(得分:0)
返回NSError的函数已更改为在Swift 2中抛出一个错误。您收到的消息表明您的代码调用了一个可以抛出的函数(特别是NSData初始化函数),但是您并没有处理这个问题。你还没有表明你的功能可以抛出;你必须做一个或另一个。
由于你的函数返回一个可选项,我建议你标记它抛出更改它返回一个非可选项。您需要使用do / try / catch来处理调用者中的错误。
enum MyAppError: ErrorType {
case fileNotFound
}
extension SKNode {
class func unarchiveFromFile(file : String) throws -> SKNode {
if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
let sceneData = NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMapped)
let archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene
archiver.finishDecoding()
return scene
} else {
throw MyAppError.fileNotFound
}
}
}
答案 1 :(得分:0)
这是我的工作修复!
extension SKNode {
class func unarchiveFromFile(file : String) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
do {
let sceneData = try NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe)
let archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene
archiver.finishDecoding()
return scene
} catch {
}
} else {
return nil
}
return nil
}
}