On 04.09.2012, at 07:52, Graham Cox wrote:

> 
> On 04/09/2012, at 3:24 PM, Gerriet M. Denkmann <gerr...@mdenkmann.de> wrote:
> 
>> I have a class with a mutable array. But from outside it should be just a 
>> read-only non-mutable array.
>> Is there a better (more elegant) way?
> 
> Just return the internal (mutable) array as an NSArray. By typing it as an 
> NSArray, you have documented your intent - that the returned value is 
> immutable.
> 
> If a client of the code is caching this array, consider making THAT property 
> a copy property.

Although this pattern is often applied for NSString properties, it's not a 
generally feasible solution. 

Since virtually any immutable class has a mutable subclass, the receiver of an 
immutable property would have to always assume that the original object can 
possibly be changed under their feet at any time, and thus has to always make a 
copy.

Furthermore, this would require that the original owner of the property MUST 
NOT alter the underlaying object until after the receiver of the property has 
made a copy. Since we are increasingly utilizing concurrency in our code, this 
cannot be guaranteed.

So, IMO, if an object provides an immutable property of an underlaying mutable 
object, this object itself shall make the copy and return that.


The problem stems from the fact, that making a mutable class a subclass of an 
immutable class, is a flawed design.


Andreas
_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to