[英]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.