Alexander Sergeev's blog

Atomic getter&setter with GCD

I’ve faced a very interesting question recently: how to write an atomic getter and setter with a copy policy by using GCD (without ARC)?

Although I could not give an answer immediately, but later on I digged a bit and found the following obvious solution based on dispatch_sync (http://www.fieryrobot.com/blog/2010/09/01/synchronization-using-grand-central-dispatch/):

- (void)setFoo:(NSObject *)newFoo {
dispatch_sync(_lockQueue, ^{
NSObject * copied = [newFoo copy];
[_foo release];
_foo = copied;
}
}

- (NSObject *)foo {
__block NSObject * result = nil;

dispatch_sync(_lockQueue, ^{
result = [[_foo retain] autorelease];
}
return result;
}

Outcome: even though you know API you still may think in old terms.

Share

Category: IT

Tagged:

Leave a Reply

You must be logged in to post a comment.




Forgot?
Register
Facebook login by WP-FB-AutoConnect