代码之家  ›  专栏  ›  技术社区  ›  Edward Hasted

Swift 2.0复制文件EXC_BAD_INSTRUCTION

  •  0
  • Edward Hasted  · 技术社区  · 9 年前

    正在将一些代码更新到2.0,我替换的copyFile例程正在返回 “致命错误:展开可选值时意外发现nil” //行是我之前的操作方式。

     class func copyFile(fileName: String) {
        let dbPath: String = getPath(fileName as String)
        let fileManager = NSFileManager.defaultManager()
        if !fileManager.fileExistsAtPath(dbPath) {
            let fromPath = NSBundle.mainBundle().pathForResource(fileName , ofType: "db")
            // let fromPath: String = NSBundle.mainBundle().resourcePath.URLByAppendingPathComponent(fileName)
            do {
                try fileManager.copyItemAtPath(fromPath!, toPath: dbPath)
            } catch _ {
            }
        }
    }
    

    我该如何解决这个问题?

    2 回复  |  直到 9 年前
        1
  •  1
  •   Inder Kumar Rathore user4622654    9 年前

    resourcePath 返回仅使用的可选值 ? 在使用任何方法之前

    let fromPath: String = NSBundle.mainBundle().resourcePath?.URLByAppendingPathComponent(fileName)
    

    而且 URLByAppendingPathComponent 不是的成员 NSString 你是说 resourceURL ?

    在这种情况下,请使用

    let fromUrl = NSBundle.mainBundle().resourceURL?.URLByAppendingPathComponent(fileName)
    let fromPath: String = (fromUrl?.path)!
    
        2
  •  0
  •   ipraba    9 年前

    我希望这能奏效

    class  func copyFile(fileName: String) {
      let dbPath: String = getPath(fileName as String)
      let fileManager = NSFileManager.defaultManager()
      if !fileManager.fileExistsAtPath(dbPath) {
        //let fromPath = NSBundle.mainBundle().pathForResource(fileName , ofType: "db")
        if let path = NSBundle.mainBundle().resourcePath
        {
          let fromPath = "\(path)/\(fileName)"
          fileManager.copyItemAtPath(fromPath, toPath: dbPath)
        }
      }
    }