[英]How to pass NSMutableArray as a reference to the part of NSMutableDictionary in Swift?
class PLCalendarEventViewController: UITableViewController {
var event: NSMutableDictionary!
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == PLCalendarEditEventLinksSegueIdentifier {
let tvc = segue.destinationViewController as PLCalendarEditEventLinksTableViewController
if var links = event.objectForKey("links") as? NSMutableArray {
tvc.data = links
}
}
}
}
But inside my PLCalendarEditEventLinksTableViewController
, when I try data.addObject("new link")
then I get following error: 但是在我的
PLCalendarEditEventLinksTableViewController
内部,当我尝试data.addObject("new link")
以下错误:
mutating method sent to immutable object
. mutating method sent to immutable object
。
All I need to do is when I change my NSMutableArray
inside PLCalendarEditEventLinksTableViewController
I change event: NSMutableDictionary
inside PLCalendarEventViewController
所有我需要做的是,当我改变我
NSMutableArray
内PLCalendarEditEventLinksTableViewController
我改变event: NSMutableDictionary
里面PLCalendarEventViewController
class PLCalendarEditEventLinksTableViewController: UITableViewController {
var data = NSMutableArray()
}
It is very simple in Objective-C, but how to do this in Swift? 在Objective-C中这非常简单,但是在Swift中如何做到这一点?
This problem can be reproduced with this simple script: 可以使用以下简单脚本重现此问题:
import Foundation
let userDefault = NSUserDefaults.standardUserDefaults()
let obj: NSMutableDictionary = ["test": NSMutableArray(array: ["foo", "bar"])]
userDefault.setObject(obj, forKey: "key")
let obj2 = userDefault.objectForKey("key") as NSMutableDictionary
if let ary = obj2["test"] as? NSMutableArray {
ary.addObject("baz")
}
You can store NSMutableArray
to NSUserDefaults
, but when retrieve it from that, it is actually a immutable array. 您可以将
NSMutableArray
存储到NSUserDefaults
,但是从中检索它时,它实际上是一个不可变的数组。 see the docs : 查看文档 :
Values returned from
NSUserDefaults
are immutable , even if you set a mutable object as the value.即使您将可变对象设置为值,从
NSUserDefaults
返回的值也是不可变的。
I don't know how actually event
constructed, but regardless of that, you have to deep copy it to mutable containers. 我不知道
event
实际构造方式,但是无论如何,您都必须将其深层复制到可变容器中。 AFAIK, the easiest way to do that is using CFPropertyListCreateDeepCopy()
. AFAIK,最简单的方法是使用
CFPropertyListCreateDeepCopy()
。 At where you construct event
property: 在构造
event
属性的位置:
event = CFPropertyListCreateDeepCopy(nil, event, CFPropertyListMutabilityOptions.MutableContainers.rawValue) as NSMutableDictionary
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.