3
votes

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
2
Are you sure that problem is related to fileArray object? Can you add exception breakpoint and check on what line app is crashing?Vlad Papko
I can't reproduce your error. Could you check the type of self.fileArray by doing CMD+CLICK on it? That way you will know if it is indeed a weird Swift bug or if self.fileArray is maybe something else than this NSMutableArray.Eric Aya
@EricD. I populate array in viewLoad from a .plist like fileArray = myDict?.valueForKey("fileList") as! NSMutableArray Do you think that might be the problemMord Fustang
Yes, it's the problem. as! NSMutableArray only makes compiler silent but not makes actual value to be mutable. You need call mutableCopy on result of myDict?.valueForKey("fileList") call.Vlad Papko
@MordFustang Can you check if this works for you fileArray = myDict?.valueForKey("fileList")!.mutableCopy() as! NSMutableArraySubbu

2 Answers

3
votes

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)

0
votes

As your array contains only a single type, I'd recommend to use Swift types, it's so much easier, var is mutable, 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()
        }))