加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

目标c – NSTimer与块 – 我是做对吗?

发布时间:2020-12-16 05:29:04 所属栏目:百科 来源:网络整理
导读:以下是NSTimer中的Objective-C类别,以进行基于块的NSTimers的触发.我看不到任何错误,但是我得到的是,我传递给schedule …方法的块正在被释放,尽管我打电话给它. 我失踪了什么 typedef void(^NSTimerFiredBlock)(NSTimer *timer);@implementation NSTimer (My
以下是NSTimer中的Objective-C类别,以进行基于块的NSTimers的触发.我看不到任何错误,但是我得到的是,我传递给schedule …方法的块正在被释放,尽管我打电话给它.

我失踪了什么

typedef void(^NSTimerFiredBlock)(NSTimer *timer);

@implementation NSTimer (MyExtension)

+ (void)timerFired:(NSTimer *)timer 
{
    NSTimerFiredBlock blk = timer.userInfo;
    if (blk != nil) {
        blk(timer);
    }
}

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds 
                                    repeats:(BOOL)repeats 
                                   callback:(NSTimerFiredBlock)blk 
{
    return [NSTimer scheduledTimerWithTimeInterval:seconds
                                            target:self
                                          selector:@selector(timerFired:)
                                          userInfo:[blk copy]
                                           repeats:repeats];
}

@end

解决方法

我发现这个代码在http://orion98mc.blogspot.ca/2012/08/objective-c-blocks-for-fun.html

做得好

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.7
      target:[NSBlockOperation blockOperationWithBlock:^{ /* do this! */ }]
      selector:@selector(main)
      userInfo:nil
      repeats:NO
];

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读