tags:

views:

194

answers:

1

Suppose I have an @property declared like this:

@property (readwrite,retain) NSObject *someObject;

And I synthesize it like this:

@synthesize someObject = _someObject;

This generates getters/setters for me. Also, according to the docs, the setter will have built in thread safety code.

Now, suppose I want to add some code to the setSomeObject: method. Is there any way that I can extend the existing on from @synthesize? I want to be able to reuse the the thread safety code that it autogenerates.

+1  A: 

What @synthesize does is equivalent to:

-(void)setSomeObject:(NSObject *)anObject {
    [anObject retain];
    [someObject release];
    someObject = anObject;
}

or

-(void)setSomeObject:(NSObject *)anObject {
    if(someObject != anObject) {
        [someObject release];
        someObject = [anObject retain];
    }
}

so you can use this code and extend the method.

However, as you said, this code might not be thread-safe.

For thread safety, you might want to take a look at NSLock or @synchronized (thanks to unwesen for pointing this out).

Can Berk Güder
@synchronized is probably a better option than NSLock - simpler at any rate.
@unwesen: you're right. why didn't I think of that?
Can Berk Güder
Don't forget the KVO calls: [self willChangeValueForKey:@"someObject"]; ... [self didChangeValueForKey:@"someObject"];
sjmulder
Adding the KVO calls aren't necessary unless you've disabled automatic KVO support by implementing +automaticallyNotifiesObserversForKey:. The generation of KVO calls is not part of @synthesize
Ashley Clark
This answer is actually not correct. The @property as declared is atomic, which means it uses a lock internally, though whether it uses a per-property lock or the equivalent of @synchronized(self) is undocumented.
Kevin Ballard