On my viewDidLoad I load from a webservice the first 5 items of an array and put them on a NSMutableArray of mine. Also on this View I have UITableViewController that displays the items of my NSMutableArray with the contents from the webservice. When I scroll to the last item of the UITableView I am loading the 5 next items from the webservice and add them to my NSMutableArray and reloading the table data in order to display all the 10 items.
The problem is that when I try to add to my existing NSMutableArray the 5 new objects from the webservice the program crashes with the message: Exception: -[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object
The way I am accessing the NSMutableArray in cellForRowAtIndexPath: is like this:
cell.textLabel.text = [[self.myMutableArray objectAtIndex:indexPath.row]objectForKey:@"name"];
Any idea on what it could be?
First, look for warnings in your compiler output. You likely have are assigning an
NSArrayto anNSMutableArrayvariable. This will often generate a warning. Your build should have no warnings in it. This is critical for ObjC code (many things you would think of as “errors” are only warnings in ObjC). If you’re ignoring warnings, then you’re going to have a lot of problems.You can have this situation without creating a warning if something is cast to
id. For example, if you fetch your “NSMutableArray” (really anNSArray) from an array or dictionary, you won’t get a warning about the type mismatch. Look for these situations. Basically, audit each point you assignmyMutableArrayand make sure that you’re actually assigning a mutable array.