块而不是performSelector:withObject:afterDelay: [英] Blocks instead of performSelector:withObject:afterDelay:

查看:99
本文介绍了块而不是performSelector:withObject:afterDelay:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常想在未来几秒钟内执行一些代码。现在,我这样解决:

I often want to execute some code a few microseconds in the future. Right now, I solve it like this:

- (void)someMethod
{
    // some code
}

并且:

[self performSelector:@selector(someMethod) withObject:nil afterDelay:0.1];

它工作,但我必须每次创建一个新的方法。是否可以使用块而不是这个?基本上我正在寻找一种方法如:

It works, but I have to create a new method every time. Is it possible to use blocks instead of this? Basically I'm looking for a method like:

[self performBlock:^{
    // some code
} afterDelay:0.1];

这对我来说非常有用。

推荐答案

没有内置的方法可以做到这一点,但通过类别添加并不难:

There's no built-in way to do that, but it's not too bad to add via a category:

@implementation NSObject (PerformBlockAfterDelay)

- (void)performBlock:(void (^)(void))block 
          afterDelay:(NSTimeInterval)delay 
{
    block = [[block copy] autorelease];
    [self performSelector:@selector(fireBlockAfterDelay:) 
               withObject:block 
               afterDelay:delay];
}

- (void)fireBlockAfterDelay:(void (^)(void))block {
    block();
}

@end

http://www.mikeash.com/pyblog/friday-qa-2009-08-14-practical-blocks.html\"> Miley Ash 的基本实施。

Credit to Mike Ash for the basic implementation.

这篇关于块而不是performSelector:withObject:afterDelay:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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