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

MIG*_*erg 9 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")
}
Run Code Online (Sandbox Code Playgroud)

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

Pau*_*son 31

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

  1. 将资源添加到项目中.

在此输入图像描述

  1. 在项目导航器中选择项目文件.

在此输入图像描述

  1. 添加新的副本文件阶段.

在此输入图像描述

  1. 步骤3中添加的阶段中,添加步骤1中的文件.您可以通过单击+按钮(带圆圈),然后导航到相关文件来完成此操作.

在此输入图像描述


在构建项目时,您现在应该能够使用访问文件的路径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.)
Run Code Online (Sandbox Code Playgroud)


Abh*_*ert 5

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

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