【问题标题】:`NSBundle.mainBundle().URLForResource` always returns `nil``NSBundle.mainBundle().URLForResource` 总是返回 `nil`
【发布时间】:2014-07-24 15:28:35
【问题描述】:

我是 Swift 新手,正在使用 Xcode 6。

我正在尝试从应用程序的 plist 文件中读取数据,但它不工作。

data.plist 文件包含在 Xcode 的 Supporting Files 组中。

我正在使用下面的代码:

var dataList = NSDictionary(contentsOfURL:NSBundle.mainBundle().URLForResource("data", withExtension:"plist"))

但是 NSURL:

NSBundle.mainBundle().URLForResource("data", withExtension:"plist")

总是返回nil

我不知道怎么了。

【问题讨论】:

  • 您确定 data.plist 文件在您的项目中吗?
  • FWIW,NSBundle.mainBundle().pathForResource 也有类似的问题。我最终使用NSBundle.mainBundle().resourcePath.stringByAppendingPathComponent 和我的文件名(带扩展名)作为参数。
  • @Kreiri 的工作就像一个魅力,有时 Xcode 只是在版本之间变得愚蠢,相同的代码在 7.1.1 中工作,更新到 7.2 失败。我的资源在 main/resources 中,但找不到它们。如果可以的话 +1 +5

标签: ios swift plist null nsbundle


【解决方案1】:

通常您会希望使用此代码来创建您的 plist。这会找到您的 plist 的路径,然后将其移动到文档目录中(如果它不存在)。如果您不移动它,则不允许对其进行写入,因此这段代码至关重要。要从 plist 中获取信息,请使用第二段代码。显然,如果你有一个数组而不是字典,你就必须改变它来处理它。

var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
    path = path.stringByAppendingPathComponent("data.plist")
    let fileManager = NSFileManager.defaultManager()
    if !fileManager.fileExistsAtPath(path) {
        let sourcePath = NSBundle.mainBundle().pathForResource("data", ofType: "plist")
        fileManager.copyItemAtPath(sourcePath, toPath: path, error: nil)
}

.

let dict = NSMutableDictionary(contentsOfFile: path) as NSMutableDictionary

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-23
    • 1970-01-01
    • 2017-03-28
    • 2015-03-05
    • 2014-08-25
    • 2016-05-17
    • 1970-01-01
    相关资源
    最近更新 更多