Fast mutation method sent to an immutable object
I just cannot fool this error, I am trying to add a string to an array as I always do in objective-c, but a quick one gives me a strange error.
var fileArray:NSMutableArray = []
alert.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
self.fileArray.addObject(self.urlTextField.text)
self.processURL()
}))
ERROR:
Application terminated due to uncaught "NSInternalInconsistencyException", reason: '- [__ NSCFArray insertObject: atIndex:]: mutation method posted to immutable object
How fileArray
unchanged? I declare this as MutableArray !!!!!!
EDIT: so the problem is how i populate the array
fileArray = myDict?.valueForKey("fileList") as! NSMutableArray
this solved the problem
fileArray = myDict?.valueForKey("fileList")!.mutableCopy() as! NSMutableArray
source to share
An array does not become mutable just because you declare it as such or because you change it with as! NSMutableArray
. An array is only mutable if it is created as a mutable array with [[NSMutableArray alloc] ....]
or by creating a mutableCopy array.
(the same applies to dictionaries, strings, NSSet and NSData)
source to share
Since your array only contains one type, I would recommend using Swift types, this is much easier, var
modified, let
is immutable
var fileArray : Array<String> = []
alert.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
self.fileArray.append(self.urlTextField.text)
self.processURL()
}))
source to share