I have an app (using retain/release, not GC) that maintains an NSArray
instance variable, which is exposed as a property like so:
@interface MyObject : NSObject
{
NSArray* myArray;
}
@property (copy) NSArray* myArray;
@end
I want to access the contents of this array from a secondary thread, which is detached using -performSelectorInBackground:withObject:
. It is possible and indeed likely that the array will change during the execution of the secondary thread.
In the secondary thread I want to do something like this:
if([self.myArray containsObject:foo])
{
//do stuff
}
From reading the threading documentation, it seems I should be able use the @synchronized
directive in the accessors like so:
@implementation MyObject
- (NSArray *)myArray
{
NSArray *result;
@synchronized(self)
{
result = [myArray retain];
}
return [result autorelease];
}
- (void)setMyArray:(NSArray *)aMyArray
{
@synchronized(self)
{
[myArray release];
myArray = [aMyArray copy];
}
}
@end
Is this all I need to do to ensure thread safety, or is it more complex?
Update: I've subsequently found a great article on Apple's site that addresses this issue in depth: http://developer.apple.com/mac/library/technotes/tn2002/tn2059.html