2015-01-05 137 views
7

使用命令行工具時,我試圖檢索存儲在名爲words.txt的文件中的單詞列表的路徑。該文件被添加到項目中,包含在項目的目標成員中,並選擇在目標的「複製文件」構建階段進行復制。 裏面Main.swift驗證碼:pathForResource在Mac OS X控制檯應用程序中返回nil

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

打印 「找不到路徑」。 mainBundle()類是否可以訪問正確的包?有關爲什麼pathForResource函數返回nil的任何想法?

回答

27

要在命令行工具中使用捆綁包,您需要確保在作爲構建階段的一部分中添加資源文件。這聽起來像你讚賞這一點,但沒有正確執行它。下面的工作在我的一個快速演示應用程序:

  1. 將資源添加到您的項目。

enter image description here

  • 選擇項目導航項目文件。
  • enter image description here

  • 添加新的拷貝文件相
  • enter image description here

  • 要你在步驟3添加的階段,從步驟1添加的文件。您可以通過點擊+按鈕(圓圈),然後導航至相關文件來完成此操作。
  • enter image description here


    當您生成項目,您現在應該能夠使用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.) 
    
    +0

    嘿它非凡非常感謝你 – ashokdy

    3

    命令行工具不使用捆綁包,它們只是一個原始可執行文件,與複製文件構建階段或NSBundle類不兼容。

    您必須將文件存儲在其他位置(例如,~/Library/Application Support)。

    相關問題