Xcode 8.1 Swift 3错误:无法转换类型' String'的值预期参数类型' UnsafeMutableRawPointer'

时间:2016-10-29 07:53:54

标签: swift xcode

包含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
        }
    }
}

1 个答案:

答案 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? { ...