[英]pathForResource returns nil in Mac OS X Console Application — 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的任何想法?
要将捆绑包与命令行工具一起使用,您需要确保在构建阶段添加资源文件。 听起来你很欣赏这一点,但没有正确执行它。 以下是一个快速演示应用程序:
在构建项目时,您现在应该能够使用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.)
命令行工具不使用软件包,它们只是一个原始可执行文件,与复制文件构建阶段或NSBundle
类不兼容。
您必须将文件存储在其他位置(例如, ~/Library/Application Support
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.