Saving CLLocation error: Mutating method sent to immutable object

爱⌒轻易说出口 提交于 2019-12-08 05:06:43

问题


I have read the other related questions, but I am stuck.

I am trying to save the last known location into a plist for later use.

Here is the error message I am receiving:

* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'

Here is my code:

var plist = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("Config", ofType: "plist"))
var dataToStore = NSKeyedArchiver.archivedDataWithRootObject(lastKnownLocation)
plist.setValue(dataToStore, forKey: "location")

The "lastKnownLocation" var is a CLLocation. The "location" key in the plist is of type "data". Could someone please assist and let me know how to do this (or how they do it if there is a better approach)? Thank you


回答1:


You need to change the NSDictionary to an NSMutableDictionary.

var path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist")
var plist: NSMutableDictionary = NSDictionary(contentsOfFile: path).mutableCopy() as NSMutableDictionary



回答2:


plist.setValue(dataToStore, forKey: "location")

You can't call setValue on an NSDictionary as it is a mutating method and NSDictionary is immutable.

var plist = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("Config", ofType: "plist"))

Change NSDictionary in this to NSMutableDictionary.



来源:https://stackoverflow.com/questions/25351366/saving-cllocation-error-mutating-method-sent-to-immutable-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!