问题
I'd like to create a macro for GCD calls like for example:
dispatch_async(dispatch_get_main_queue(), ^{
stuff....
});
the macro could look something like this: main(^{...})?
Not sure how to write it. Any suggestion?
thank you
回答1:
You can define macros like this:
#define ASYNC(...) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ __VA_ARGS__ })
#define ASYNC_MAIN(...) dispatch_async(dispatch_get_main_queue(), ^{ __VA_ARGS__ })
First one will invoke the code asynchronously on unspecified thread (do all long running tasks using it) and the second one will invoke the block asynchronously on the main thread (do all UI related stuff using it).
You can combine both. Let's say you want to grab something from the network and update UI, you can write:
ASYNC({
NSString *result = [[NSString alloc] initWithContentsOfURL: ...];
ASYNC_MAIN({
self.myTextField.string = result;
[result release];
});
});
You add curly braces to make Xcode indent the code properly.
Please note where retain/release calls are made. This is powerful technique which will make your code readable.
回答2:
Suggestion: don't. Among other things, it'll screw up line numbers in debugging.
You can actually define a normal function that will do the same thing, if you want, something like
typedef void(^VoidBlock)();
void on_main(VoidBlock block) {
dispatch_async(dispatch_get_main_queue(), block);
}
This has the advantage that you don't lose line numbers for the block during debugging. I've even done things like
void on_main(VoidBlock block) {
if (dispatch_get_current_queue() == dispatch_get_main_queue()) {
block();
} else {
dispatch_sync(dispatch_get_main_queue(), block);
}
}
which I can call either from the main queue or not.
You really want to avoid putting code blocks in macro arguments. If you do and have to debug that code, you'll hate yourself. (A bit tongue in cheek, but it really is painful if you have to debug any macro that expands to multiple lines of code.)
来源:https://stackoverflow.com/questions/9435889/write-macros-for-gcd-calls