Re: Accessing array in thread safe way
Re: Accessing array in thread safe way
- Subject: Re: Accessing array in thread safe way
- From: Charles Srstka <email@hidden>
- Date: Thu, 08 Mar 2012 14:02:41 -0600
On Mar 8, 2012, at 8:22 AM, CoGe - Tamas Nagy wrote:
> Maybe this will helps you, here is my thread-safe subclass of NSMutableArray:http://code.google.com/p/cogeopensource/source/browse/trunk/CoGeOpenSource/CoGeThreadSafeMutableArray.m
>
> Works well for my project.
IMO, if anything is overkill for something like this, it’s subclassing a mutable array. What you should be doing is implementing accessors to get to the data stored in the array. If you don’t need an NSMutableArray interface, you can just implement methods like -objectAtIndex: and -insertObject:atIndex:, etc. to get at the data, like all of the collection classes do. If you do need an NSArray interface (for bindings, for example), then you should implement the KVO indexed accessors, for a few reasons:
- Using accessors ensures proper encapsulation of your data; you can later change the implementation under the hood from an NSMutableArray to something completely different if you desire, without breaking the interface.
- If you later decide you need to be informed when something changes the contents of your array, it’s much easier to do with KVO than with vending an NSMutableArray.
- It’s generally not a good idea to expose the internal state of your object, in any case.
- If you’re planning to use bindings to access this property, you’re going to want to implement the KVO indexed accessors like objectIn<key>AtIndex:, insertObject:in<key>AtIndex:, etc. anyway for performance reasons — if you don’t, the bindings mechanism will basically replace the whole array every time something changes, by calling the setter for the array.
- If you really need an NSMutableArray interface to the object’s data, it’s only one line of code to create an NSMutableArray proxy once the KVO indexed accessor methods are already implemented, as opposed to adding a whole new NSMutableArray subclass.
Charles
_______________________________________________
Cocoa-dev mailing list (email@hidden)
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:
This email sent to email@hidden