简体   繁体   English

NSMutableArray访问器返回NSArray

[英]NSMutableArray accessor returning NSArray

I have a NSMutableArray 我有一个NSMutableArray

@property (copy, nonatomic) NSMutableArray *childrenArray;

Now i initialize it like this: 现在我像这样初始化它:

self.childrenArray = [NSMutableArray arrayWithArray:children];

children is also nsmutable above, 孩子们也很聪明,

Now when i was removing an object from children array i got this error: 现在当我从children数组中删除一个对象时,我收到了这个错误:

[__NSArrayI removeObjectAtIndex:]: unrecognized selector sent

I instantly understood that my remove was being called on NSArray, so my query is why my accessor is returning NSArray as it is supposed to return NSMutableArray. 我立即明白我的删除是在NSArray上调用的,所以我的查询是我的访问者返回NSArray的原因,因为它应该返回NSMutableArray。

Thanks, 谢谢,

First, a copy @property literally sends copy to the object being set. 首先, copy @property逐字地将copy发送到正在设置的对象。 A mutable collection responds to copy by creating an immutable copy. 可变集合响应copy通过创建一个不可改变的副本。 Mutable copying is rife with edge cases (of which many have been covered in other SO questions). 可变复制充斥着边缘案例(其中很多已经被其他SO问题所涵盖)。

Secondly, you really really don't want properties providing access to mutable state within an object. 其次,你真的真的不想提供对象中获取可变状态属性。 And you probably don't want to vend mutable collection classes. 你可能不想出售可变的集合类。


Blunt: 钝:

Sending copy to a mutable collection returns an immutable copy. copy发送到可变集合将返回不可变副本。 A copy property will not preserve mutability. copy属性不会保留可变性。

Manually implementing the setter/getter to set/return mutable instances is probably wrong. 手动实现setter / getter来设置/返回可变实例可能是错误的。


Think of it this way: 想一想:

You have a class named "Person" that has an property named "firstName". 您有一个名为“Person”的类,它具有名为“firstName”的属性。 If that property were mutable, someone might say: 如果该属性是可变的,有人可能会说:

 [[aPerson firstName] setString:@"Joe"];

Ie would you want someone to be able to change your first name without any kind of a notification that they did so? 也就是说,你希望有人能够在没有任何通知的情况下更改你的名字吗? Probably not. 可能不是。 But that is exactly what you are allowing by exposing the state of an object in a mutable container. 但这正是您通过在可变容器中公开对象的状态而允许的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM