为GCD通话编写宏吗? [英] Write macros for GCD calls?

查看:74
本文介绍了为GCD通话编写宏吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为GCD调用创建一个宏,例如:

I'd like to create a macro for GCD calls like for example:

dispatch_async(dispatch_get_main_queue(), ^{
    stuff....
});

宏可能看起来像这样: main(^ {...})?

the macro could look something like this: main(^{...})?

不确定如何编写.有什么建议吗?

Not sure how to write it. Any suggestion?

谢谢

推荐答案

您可以定义如下宏:

#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__ })

第一个将在未指定的线程上异步调用代码(使用它来执行所有长时间运行的任务),第二个将在主线程上异步调用代码块(使用它来执行所有与UI相关的工作).

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).

您可以将两者结合使用.假设您要从网络中获取某些内容并更新UI,可以编写:

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];
  });
});

添加大括号以使Xcode正确缩进代码.

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.

这篇关于为GCD通话编写宏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆