【问题标题】:Swift Dictionary filled but still emptySwift Dictionary 已填满但仍为空
【发布时间】:2015-02-09 22:30:25
【问题描述】:

我已经解决一个问题太久了,我真的不明白为什么会发生这种情况。我在网上搜索了解决方案,我已经尝试了每一个,但我仍然遇到这个问题。我在 Swift 中初始化了一个字典,然后向它添加了一些值,但是在我添加了键/值之后,字典是空的(在调试模式下检查),稍后在尝试从中读取时在代码中也是 nil .这是我当前的代码:

我首先得到要在其中添加字典的 plist:

var path = NSBundle.mainBundle().pathForResource("Questions", ofType: "plist")
var dict = NSDictionary(contentsOfFile: path!)!
var questionsArr = dict.objectForKey("Math") as NSArray
var questionsMutableArray:NSMutableArray = questionsArr.mutableCopy() as NSMutableArray

然后我创建并向我的字典添加值

//I have also tried with this and got the same result: var newDict = Dictionary<String, String>()
var newDict = [String: String]()
newDict["Question"] = "What is 1+1"
newDict["A"] = "One"
newDict["B"] = "Two"
newDict["C"] = "Three"

这里的调试模式下,newDict 似乎是空的。 然后我将字典写入我的 plist:

questionsMutableArray.addObject(newDict)
questionsMutableArray.writeToFile(path!, atomically: true)

稍后在代码中,我得到了这样的 plist(在我没有添加 newDict 之前它工作过:

var path = NSBundle.mainBundle().pathForResource("Questions", ofType: "plist")
var dict = NSDictionary(contentsOfFile: path!)!

在最后一行 (NSDictinoary(contentsOfFile:path!)!我收到此错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

有人知道为什么会这样吗? 帮助将不胜感激!

EDIT4)中的解决方案

1. I'm getting an array of dictionaries from my plist (Questions).
2. I add a new dictionary to my array of dictionaries.
3. I write/save it to the plist.
4. I get the array from the plist again and investigate the content of it.
5. The new dictionary I just added is not there.

这是代码:

1) questionsArr 为空

var bundlepath:NSString = NSBundle.mainBundle().pathForResource("Questions", ofType: "plist")!

        var dict = NSMutableDictionary(contentsOfFile: bundlepath)!
        var questionsArr = dict.objectForKey("Math") as NSArray
        var questionsMutableArray:NSMutableArray = questionsArr.mutableCopy() as NSMutableArray

2) questionsMutableArray 为空,现在包含新问题。

var newDict = [String: String]()
    newDict["QuestionTitle"] = "What is 1+1?"
    newDict["A"] = "One"
    newDict["B"] = "Two"
    newDict["C"] = "Three"

let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
var path:NSString = documentsPath.stringByAppendingPathComponent("Questions.plist");

questionsMutableArray.addObject(newDict)
dict["Math"] = questionsMutableArray

3)

let didItSave = dict.writeToFile(path, atomically: true)

4) questionsArr 仍然为空。如果我使用 'path' 而不是 'bundlepath' 就可以了!

dict = NSMutableDictionary(contentsOfFile: bundlepath)! //<- I USED 'path' INSTEAD OF 'bundlepath' and now it works!
    questionsArr = dict.objectForKey("Math") as NSArray

【问题讨论】:

  • 你能在你发现它为零的地方显示代码吗?发布的代码无助于识别问题
  • 不确定它是如何在 swift 中工作的,但是如果你想向它添加东西,你的字典需要是“可变的”。
  • Swift 中集合的可变性取决于您将字典分配给变量还是常量,而不是像 Objective-C 中的类名。
  • NSDictionary 可能无法加载文件。确保路径正确。
  • 你的 plist 文件是一个字典数组,所以当你检索它时,你必须将它作为一个 NSArray 检索。

标签: ios xcode swift dictionary


【解决方案1】:

您正在尝试编写 iOS Bundle。 iOS Bundle 是只读的,不能写。

我建议你写在 Document 目录 试试这个方法

 var bundlepath:NSString= NSBundle.mainBundle().pathForResource("Questions", ofType: "plist")

    var dict = NSDictionary(contentsOfFile: bundlepath)!
    var questionsArr = dict.objectForKey("Math") as NSArray
    var questionsMutableArray:NSMutableArray = questionsArr.mutableCopy() as NSMutableArray


    //I have also tried with this and got the same result: var newDict = Dictionary<String, String>()
    var newDict = [String: String]()
    newDict["Question"] = "What is 1+1"
    newDict["A"] = "One"
    newDict["B"] = "Two"
    newDict["C"] = "Three"

    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
    var path:NSString = documentsPath.stringByAppendingPathComponent("Questions.plist");



questionsMutableArray.addObject(newDict)

//将数组分配回字典。 dict["Math"]=questionsMutableArray

dict.writeToFile(path!, atomically: true)

    var dictFromDisk = NSDictionary(contentsOfFile: path)!

【讨论】:

  • 执行第三行时出现此错误:fatal error: unexpectedly found nil while unwrapping an Optional value
  • 基本上你正在尝试从包中加载 plist 并将字典添加到数组并保存到磁盘。但是您必须从 Document 目录加载 plist 文件以供下次读取,然后您的数据将保持一致。
  • 我明天试试,让你知道。无法自动取款机。提前致谢!
  • 好的,如果有任何问题,请告诉我,我会帮你解决。
  • 嘿 @Shashi3456643 ,在最后一行 (var dictFromDisk = NSDictionary(contentsOfFile:path)!) 我再次收到此错误:fatal error: unexpectedly found nil while unwrapping an Optional value。 writeToFile 似乎工作,因为它说 writetofile 成功。
【解决方案2】:

首先,当您检索 plist 时,将其检索到 NSMutableDictionary

var dict = NSMutableDictionary(contentsOfFile: path!)!

然后,一旦您创建了数组,请将您的字典数学键设置为它。

dict["math"] = questionsMutableArray

然后将字典写回你的路径。可能想看看它是否有效,writeToFile 返回一个布尔值。

let didItSave = dict.writeToFile(path!, atomically: true)

【讨论】:

  • 这适用于writeToFile 部分。我可以看到我的新字典保存在dict["math"] 中。但是在我将它写入文件然后再次获取它(读取 plist)之后,新的字典不存在!
【解决方案3】:

您的 plist 文件是一个字典数组,因此当您检索它时,您必须将其检索为 NSArray,然后将其转换为 Dictionary&lt;String, String&gt; 的数组

let array = NSArray(contentsOfFile: NSBundle.mainBundle().pathForResource("Questions", ofType: "plist")!) as [[String: String]]

然后,您可以使用以下方法访问此数组中的特定字典:

let someDict = array[someIndex]

【讨论】:

  • 我在 Question.plist 中的“根”键是一个包含数组的字典,每个数组也包含许多字典。
  • 为什么不把你的根对象变成一个数组呢?
  • 我其实不知道我为什么这样做,但现在就是这样。问题是我的 newDict 在我初始化它并向它添加项目后是空的。我不明白为什么。
【解决方案4】:

编辑了我的答案:

您正在使用以下行保存数组

questionsMutableArray.writeToFile(path!, atomically: true)

但随后尝试将其加载为字典。您应该将问题数组设置为字典的“数学”键,然后像这样保存字典本身以使您的读写兼容。

dict["Math"] = questionsMutableArray 
dict.writeToFile(path!, atomically: true)

【讨论】:

  • 我在 Question.plist 中的“根”键是一个包含数组的字典,每个数组也包含许多字典。
  • 您正在阅读来自 dict["math"] 的问题,但是您正在将新问题添加到不同的数组并用该数组替换旧的 plist。因此,您的 plist 文件不再是字典。您当前的写入和读取不兼容。请检查我编辑的答案以解决问题
猜你喜欢
  • 1970-01-01
  • 2019-03-08
  • 1970-01-01
  • 1970-01-01
  • 2012-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多