How to safely access the contents of an NSArray property from a secondary stream?

I have an application (using save / release, not GC) that supports an instance variable NSArraythat displays as a property like this:

@interface MyObject : NSObject
{
    NSArray* myArray;
}
@property (copy) NSArray* myArray;
@end

I want to access the contents of this array from a secondary stream, which is disconnected using -performSelectorInBackground:withObject:. It is possible and possible 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 documentation on streams, it seems like I should use the directive @synchronizedin such accessories:

@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 that all I need to ensure thread safety, or is it more complicated?

: Apple, : http://developer.apple.com/mac/library/technotes/tn2002/tn2059.html

+3
1

, - . , .

, " " , , . , NSMutableStrings, , :

NSMutableString *foo = [myObject.myArray objectAtIndex:0];
[foo appendString:@"foo"];

-

NSMutableString *bar = [myObject.myArray objectAtIndex:0];
[bar appendString:@"bar"];

( , ), foo/bar ( ) , ' appendString ' @synchronized.

, . @ , . .

+5

Source: https://habr.com/ru/post/1732286/


All Articles