3 ms·
Objective-C can sometimes be pretty verbose, yes, but that's a very contrived block example, especially since it doesn't really relate to concurrency in any way
by schrototo 15y ago
Objective-C can sometimes be pretty verbose, yes, but that's a very contrived block example, especially since it doesn't really relate to concurrency in any way.
A more real-world example employing blocks with GCD would be:
dispatch_queue_t queue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
// do some time-consuming work
dispatch_async(dispatch_get_main_queue() ^{
// do stuff on the main thread, like updating UI
});
});
That's actually pure C. Typical block usage with Cocoa would be something like:
[myArray enumerateObjectsWithOptions:NSEnumerationConcurrent
usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
// do something with obj concurrently
}];
- headhuntermdk 15y agoyou forgot a BOOYAH!! at the end of that
- fleitz 15y agoCan you really do the latter in Obj-C? As I understood it you needed to copy and autorelease the block to move it from stack allocation to heap allocation.
- schrototo 15y agoThat's right, but if the receiver needs to have the block on the heap for whatever reason, it's his responsibility to take care of that. Blocks are really no different from any other method argument.