0

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?

3
  • Can you paste the declaration of your myMutableArray property? Commented Jun 21, 2012 at 14:48
  • 1
    please show the code of how you initialize the array :-) Commented Jun 21, 2012 at 14:48
  • 4
    My guess is that you don't have an NSMutableArray, but a plain old NSArray. Just because the pointer is named "mutable" does not make the object mutable. Commented Jun 21, 2012 at 14:48

1 Answer 1

3

First, look for warnings in your compiler output. You likely have are assigning an NSArray to an NSMutableArray variable. 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 an NSArray) from an array or dictionary, you won't get a warning about the type mismatch. Look for these situations. Basically, audit each point you assign myMutableArray and make sure that you're actually assigning a mutable array.

Sign up to request clarification or add additional context in comments.

1 Comment

I was setting the result of the webservice call directly to the nsmutablearray. Now I allocated and initialized it first and then added the objects one by one, and it worked fine. Thanks a lot! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.