Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift mutating method sent to immutable object

I just can't wrap my head around this error, I am trying to add a string to an array like I always do in objective-c, but swift gives me a weird error.

var fileArray:NSMutableArray = []

alert.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
            self.fileArray.addObject(self.urlTextField.text)
            self.processURL()
        }))

ERROR:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'

How fileArray is immutable? I declare it as MutableArray !!!!!!

EDIT::: so turns out problem is the way I populate the array

fileArray = myDict?.valueForKey("fileList") as! NSMutableArray

this solved the problem

fileArray = myDict?.valueForKey("fileList")!.mutableCopy() as! NSMutableArray
like image 613
Mord Fustang Avatar asked Feb 14 '26 16:02

Mord Fustang


1 Answers

An array does not become mutable just because you declare it as such or because you cast it as mutable with as! NSMutableArray. An array is only mutable if it is created as a mutable array with [[NSMutableArray alloc] ....] or by making a mutableCopy of an array.

(the same goes for dictionaries, strings, NSSet and NSData)

like image 86
Michael Avatar answered Feb 16 '26 08:02

Michael