Skip to content

Instantly share code, notes, and snippets.

@JimRoepcke
Created July 7, 2012 07:46
Show Gist options
  • Save JimRoepcke/3065296 to your computer and use it in GitHub Desktop.
Save JimRoepcke/3065296 to your computer and use it in GitHub Desktop.
@synchronized doesn't retain monitored object under MRC
__block id foo = [MyObject new];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"block entering synchronized");
@synchronized(foo) {
NSLog(@"running in synchronized");
sleep(10);
NSLog(@"running [foo self]");
[foo self];
NSLog(@"ran [foo self]");
}
NSLog(@"block exited synchronized");
});
sleep(1);
NSLog(@"running at top level, releasing foo");
[foo release];
NSLog(@"running at top level, released foo");
@JimRoepcke
Copy link
Author

2012-07-07 00:44:23.115 Synchronized[39663:11e03] block entering synchronized
2012-07-07 00:44:23.116 Synchronized[39663:11e03] running in synchronized
2012-07-07 00:44:24.116 Synchronized[39663:fb03] running at top level, releasing foo
2012-07-07 00:44:24.117 Synchronized[39663:fb03] releasing MyObject
2012-07-07 00:44:24.117 Synchronized[39663:fb03] running at top level, released foo
2012-07-07 00:44:24.119 Synchronized[39663:fb03] Application windows are expected to have a root view controller at the end of application launch
2012-07-07 00:44:33.118 Synchronized[39663:11e03] running [foo self]
(lldb)

@JimRoepcke
Copy link
Author

Does this mean you should retain foo before @synchronized(foo) and release afterwards? Does that mean you need to wrap all of that in a try/catch in case it does throw so that foo can be released in that case too?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment