【发布时间】: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