简体   繁体   English

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

[英]pathForResource returns nil in Mac OS X Console Application — Swift

Working on a command line tool, I am trying to retrieve the path of a list of words stored in a file called words.txt. 在命令行工具上,我试图检索存储在名为words.txt的文件中的单词列表的路径。 The file is added to the project, included in the project's Target Membership, and selected to copy during the target's Copy Files build phase. 该文件将添加到项目中,包含在项目的目标成员资格中,并选择在目标的“复制文件”构建阶段进行复制。 Inside Main.swift this code: 在Main.swift里面这段代码:

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

prints "Could not find path". 打印“无法找到路径”。 Is the mainBundle() class function the correct bundle to access? mainBundle()类函数是否可以访问正确的bundle? Any thoughts on why the the pathForResource function returns nil? 有关为什么pathForResource函数返回nil的任何想法?

To use bundles with command line tools you need to make sure you're adding the resource files as part of the build phase. 要将捆绑包与命令行工具一起使用,您需要确保在构建阶段添加资源文件。 It sounds like you appreciate this, but haven't executed it correctly. 听起来你很欣赏这一点,但没有正确执行它。 The following worked for me in a quick demo app: 以下是一个快速演示应用程序:

  1. Add the resource to your project. 将资源添加到项目中。

在此输入图像描述

  1. Select the project file in the project navigator. 在项目导航器中选择项目文件。

在此输入图像描述

  1. Add a new copy file phase . 添加新的副本文件阶段

在此输入图像描述

  1. To the phase you added in step 3 , add the file from step 1 . 步骤3中添加的阶段中,添加步骤1中的文件。 You do this by clicking the + button (circled), and then navigating to the file in question. 您可以通过单击+按钮(带圆圈),然后导航到相关文件来完成此操作。

在此输入图像描述


When you build the project, you should now be able to access the file's path using NSBundle . 在构建项目时,您现在应该能够使用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.)

Command Line Tools do not use bundles, they are just a raw executable file and are not compatible with the copy files build phase or the NSBundle class. 命令行工具不使用软件包,它们只是一个原始可执行文件,与复制文件构建阶段或NSBundle类不兼容。

You will have to store the file somewhere else (eg, ~/Library/Application Support ). 您必须将文件存储在其他位置(例如, ~/Library/Application Support )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM