在命令行工具上工作,我试图检索存储在名为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
要将捆绑包与命令行工具一起使用,您需要确保在构建阶段添加资源文件.听起来你很欣赏这一点,但没有正确执行它.以下是一个快速演示应用程序:



在构建项目时,您现在应该能够使用访问文件的路径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)
命令行工具不使用包,它们只是一个原始的可执行文件,与复制文件构建阶段或NSBundle类不兼容。
您必须将文件存储在其他地方(例如,~/Library/Application Support)。
| 归档时间: |
|
| 查看次数: |
4758 次 |
| 最近记录: |