pathForResource在Mac OS X控制台应用程序 - Swift中返回nil

时间:2015-01-05 00:20:35

标签: macos cocoa swift

使用命令行工具,我试图检索存储在名为words.txt的文件中的单词列表的路径。该文件将添加到项目中,包含在项目的目标成员资格中,并选择在目标的“复制文件”构建阶段进行复制。 在Main.swift里面这段代码:

if let path = NSBundle.mainBundle().pathForResource("words", ofType: "txt") {
  println("Path is \(path)")
} else {
  println("Could not find path")
}

打印“无法找到路径”。 mainBundle()类函数是否可以访问正确的bundle?有关为什么pathForResource函数返回nil的任何想法?

2 个答案:

答案 0 :(得分:30)

要将捆绑包与命令行工具一起使用,您需要确保在构建阶段添加资源文件。听起来你很欣赏这一点,但是没有正确地执行它。以下内容适用于快速演示应用程序:

  1. 将资源添加到项目中。
  2. enter image description here

    1. 在项目导航器中选择项目文件。
    2. enter image description here

      1. 添加新的复制文件阶段
      2. enter image description here

        1. 第3步中添加的阶段,从第1步添加文件。您可以通过单击 + 按钮(带圆圈),然后导航到相关文件来执行此操作。
        2. enter image description here


          构建项目时,您现在应该可以使用NSBundle访问文件的路径。

          import Foundation
          
          let bundle = NSBundle.mainBundle()
          let path = bundle.pathForResource("numbers", ofType: "txt")
          
          if let p = path {
              let string = NSString(contentsOfFile: p,
                  encoding: NSUTF8StringEncoding,
                  error: nil)
              println(string)
          } else {
              println("Could not find path")
          }
          
          // Output -> Optional(I am the numbers file.)
          

答案 1 :(得分:3)

命令行工具不使用捆绑包,它们只是一个原始可执行文件,与复制文件构建阶段或NSBundle类不兼容。

您必须将文件存储在其他位置(例如~/Library/Application Support)。