简体   繁体   中英

NSMutableArray accessor returning NSArray

I have a 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:

[__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.

Thanks,

First, a copy @property literally sends copy to the object being set. A mutable collection responds to copy by creating an immutable copy. Mutable copying is rife with edge cases (of which many have been covered in other SO questions).

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. A copy property will not preserve mutability.

Manually implementing the setter/getter to set/return mutable instances is probably wrong.


Think of it this way:

You have a class named "Person" that has an property named "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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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