如何处理“发送到不可变对象的变异方法”异常?

时间:2010-04-28 11:05:01

标签: iphone objective-c

我正在上一个名为Customer的课程。

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

object.customerName
object.customerAddress 
object.customerContactList

我将customerContactList声明为NSMutableArray并分配并初始化。

现在我在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];

即使是NSMutableArray,我也会遇到异常。请帮帮我。

谢谢你, Madan Mohan

2 个答案:

答案 0 :(得分:3)

我是猜测,因为正如Williham Totland所说,我们需要看到你的代码。如何声明,实现和分配customerContactList属性?

我的猜测是你在阵列上使用copy的地方。如果您将copy发送到NSMutalbeArray,您将获得不可变副本。如果您的财产被宣布:

@property (copy) NSArray* customerContactList

使用它时,你会得到一个不可变的数组。如果你这样声明,你甚至可能得到一个不可变数组(我不确定编译器有多聪明):

@property (copy) NSMutableArray* customerContactList

答案 1 :(得分:1)

你一直在问这个问题,你会得到同样的答案:“Izit?”。在此之前您需要进一步帮助之前,您需要实际显示更多代码,例如Customer的接口声明。

> > 以您描述的方式直接在对象上访问集合对象几乎不被视为犹太教。

另一件事:你的属性真的不需要在他们的名字中有类名;而不是Customer你应该- (void)addToContactList:(id)contact等等。使代码更具可读性。

这有点重复:如果你有一个Customer *object; object.customerName;,你就不能得到那个例外。这个例外是明确证明你所拥有的,实际上是 Customer *customer; customer.name;;并且不能。这是有关例外的功能。这就是异常,确实和意味着什么。这是例外的本质,如果你愿意,那就是成为或者 raison d'etre 的原因。如果不清楚:您尝试添加的阵列不可变。它是 不可变