Madan Mohan
Madan Mohan

Reputation: 8810

How to handle "mutating method sent to immutable object" exception?

I am having a class called Customer.

Customer *object; //in this object i have the following data varialbles.

object.customerName
object.customerAddress 
object.customerContactList

I declared customerContactList as NSMutableArray and also allocated and initialized.

Now I am adding or deleting from contactList.

//Adding.
[object.customerContactList addObject:editcontacts];// here editcontacts one of the object in contactList.

//Deleting.
[object.customerContactList removeObjectAtIndex:indexPath.row];
[theTableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];

I am getting exception even it is NSMutableArray. Please help me.

Thank You, Madan Mohan

Upvotes: 1

Views: 2491

Answers (2)

JeremyP
JeremyP

Reputation: 86651

I'm jut guessing, because as Williham Totland said, we need to see your code. How is the customerContactList property declared, implemented and assigned?

My guess is that somewhere you are using copy on the array. If you send copy to an NSMutalbeArray you'll get an immutable copy back. If your property is declared:

@property (copy) NSArray* customerContactList

you'll get an immutable array back when you use it. You might even get an immutable array if you declare it thus (I'm not sure how clever the compiler is):

@property (copy) NSMutableArray* customerContactList

Upvotes: 3

Williham Totland
Williham Totland

Reputation: 29009

You keep asking this question, and you keep getting the same answer: "Izit?". Before you can be helped any further on this point, you need to actually show some more code, like the interface declaration for Customer.

What you should do, at this juncture, is to add a method to Customer along the lines of - (void)addToContactList:(id)contact. Accessing collection objects directly on an object in the manner you are describing is hardly considered kosher.

And another thing: your properties really don't need to have the class name in their name; rather than Customer *object; object.customerName; you should have Customer *customer; customer.name; and so on. Makes for far more readable code.

And this bears repeating: You cannot get that exception if you have an NSMutableArray. That exception is unequivocal proof that what you have, in fact, is not an NSMutableArray; and cannot be. This is the function of the exception in question. This is what the exception is, does, and means. This is the essence of the exception, it's reason for being, or raison d'etre, if you will. In case it wasn't clear: The array you are attempting to add to is not mutable. It is immutable.

Upvotes: 1

Related Questions