What is the difference between a __weak and a __block reference?

From the docs about __block __block variables live in storage that is shared between the lexical scope of the variable and all blocks and block copies declared or created within the variable’s lexical scope. Thus, the storage will survive the destruction of the stack frame if any copies of the blocks declared within the frame … Read more

Block_release deallocating UI objects on a background thread

You can use the __block storage type qualifier for such a case. __block variables are not automatically retained by the block. So you need to retain the object by yourself: __block UIViewController *viewController = [myViewController retain]; dispatch_async(backgroundQueue, ^{ // Do long-running work here. dispatch_async(dispatch_get_main_queue(), ^{ [viewController updateUIWithResults:results]; [viewController release]; // Ensure it’s released on main … Read more

How does a Block capture the variables outside of its enclosing scope?

It’s actually fairly straightforward and described in Clang’s Block Implementation Spec, in the “Imported Variables” section. When the compiler encounters a Block like: ^{ if( numBalloons > numClowns) abort(); } it creates a literal structure that includes — among other things — two elements that are important here. There’s a function pointer to the executable … Read more

Checking Objective-C block type?

Can do, kinda sorta. But first, let’s disambiguate. -[NSObject isKindOfClass:] can tell you it’s a block, and that’s about it. E.g. I believe this line of code — ostensibly & unfortunately A BAD IDEA — will return YES for blocks on present Lion & iOS 5.x: [myBlock isKindOfClass:NSClassFromString(@”NSBlock”)] That won’t help you distinguish the block’s … Read more

How can I verify that I am running on a given GCD queue without using dispatch_get_current_queue()?

Assign whatever identifier you want using dispatch_queue_set_specific(). You can then check your identifier using dispatch_get_specific(). Remember that dispatch_get_specific() is nice because it’ll start at the current queue, and then walk up the target queues if the key isn’t set on the current one. This usually doesn’t matter, but can be useful in some cases.

How to cancel NSBlockOperation

Doh. Dear future googlers: of course operation is nil when copied by the block, but it doesn’t have to be copied. It can be qualified with __block like so: //THIS MIGHT LEAK! See the update below. __block NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{ while( ! [operation isCancelled]){ //do something… } }]; UPDATE: Upon further meditation, it … Read more