2015-01-05 144 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)。

    相关问题