我有一个应用程序周围,需要坚持的字典数组的数组。 我不能将它保存到NSUserDefaults。 我可能会使用CoreData,如果我有它的经验,但它似乎矫枉过正,我只需要在启动时收集数据,并保存一次关闭。如何保存和检索字典数组的数组
所以我想弄清楚如何写这个保存到一个plist文件(如果可能的话)。 并在应用程序启动时检索它。
数据:
// Declare var
var recordingsDictionaryArray = [[:]]
// Populate many times during app use
recordingsDictionaryArray.insert(["name":saveRecordingField.stringValue, "date":NSDate(), "path":recorder.url], atIndex: 0)
所以词典包含字符串的NSDate的混合物,而NSURL
可这在我的applicationSupport文件被保存到一个plist文件..? 希望不会在启动时保存并重新构建它时将其分开。
我正在尝试一个例子,但我不能得到它的工作,如果我没有参考[0]的数据变种。如果我只是说VAR数据= recordingsDictionaryArray我得到的错误:
func applicationWillTerminate(aNotification: NSNotification) {
// add some dummy content to the empty recordingsDictionaryArray
recordingsDictionaryArray.insert(["name":"Recording One", "date":NSDate(), "path":"dummy path"], atIndex: 0) // dummy content
recordingsDictionaryArray.insert(["name":"Recording Two", "date":NSDate(), "path":"another dummy path"], atIndex: 0) // dummy content
recordingsDictionaryArray.insert(["name":"Recording Three", "date":NSDate(), "path":"final dummy path"], atIndex: 0) // dummy content
// check the count
var thecount = recordingsDictionaryArray.count
println(thecount)
var data = recordingsDictionaryArray[0] // if i do not add reference to item [0] data errors below
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
var path = paths.stringByAppendingPathComponent("data.plist")
var fileManager = NSFileManager.defaultManager()
if (!(fileManager.fileExistsAtPath(path)))
{
var bundle: NSString = NSBundle.mainBundle().pathForResource("recordings", ofType: "plist")!
fileManager.copyItemAtPath(bundle, toPath: path, error:nil)
}
data.objectForKey(data)
data.writeToFile(path, atomically: true)
// I only get "Recording 3" saved to the plist
}
再回答下面的1: 我觉得我是接近NSUserDefaults的与到达那里,但不知道如何让mutableRetrievedDictionary回recordingsDictionaryArray为它是在保存之前。
// save
NSUserDefaults.standardUserDefaults().setObject(recordingsDictionaryArray, forKey: "recordingsArray")
NSUserDefaults.standardUserDefaults().synchronize()
// retrieve
var mutableRetrievedDictionary: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("recordingsArray")?.mutableCopy()
请注意,从NSUserDefaults返回的数据总是不可变的,需要再次更改为mutable。 – AMAN77 2014-11-21 15:07:04