2015-11-18 24 views
-1
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

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 
} 
+0

你好, 所以我没有进行更改,并使其 如果让PATH = NSBundle.mainBundle()pathForResource(文件作为字符串,ofType。 :“SKS”){// 路径是安全 } 但现在它给我用悬而未决的标识符“路径” 也与第一选项,错误仍然 感谢您的帮助:) – Domo

+0

您必须将其余的代码放到* path安全*范围内。而且我怀疑还有另一个问题,当'SKNode'被预期时会返回'GameScene'。 – vadian

+0

'让sceneData = NSData的(contentsOfFile:路径,选择:.DataReadingMappedIfSafe,误差:无) VAR归档= NSKeyedUnarchiver(forReadingWithData:sceneData) archiver.setClass(s​​elf.classForKeyedUnarchiver(),forClassName: “SKScene”) 设现场= archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey)作为GameScene archiver.finishDecoding() 返回现场 }' 这是我的全部代码,我是很新的快捷,我不知道在所有的如何解决它。我花了很长时间尝试 – Domo

相关问题