NSTimer的更好替代品 [英] Better alternative for NSTimer

查看:118
本文介绍了NSTimer的更好替代品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道,使用比NSTimer更好,更有效的功能吗?我的ViewDidLoad函数有这样的NSTimer代码:

I'm just wondering, is there a better, more efficient function to use than NSTimer? I have a NSTimer code like this on my ViewDidLoad function:

[NSTimer scheduledTimerWithTimeInterval:900.0f target:self selector:@selector(methodToRun) userInfo:nil repeats:YES];

使用函数methodToRun:

With the function methodToRun:

-(void)methodToRun {
     if(currentTime == presetTime) {
        //do something
     }
}

这很好用,但问题是,这会占用大量内存而且我会收到内存警告。那么,什么是更好,更有效和更少内存消耗的方法来连续触发我的methodToRun来检查currentTime是否等于presetTime?

This works fine but the problem is, this eats up a lot of memory and I am getting memory warnings. So, what's a better, more efficient and less memory consuming way of triggering my methodToRun continuously to check if the currentTime is equal to presetTime?

推荐答案

您可以使用 dispatch_after

使用dispatch_after方法和指向self的弱指针可以实现对此的替代解决方案。

An alternative solution to this can be achieved by using the dispatch_after method and a weak pointer to self.

__weak id weakSelf = self;
__block void (^timer)(void) = ^{

    double delayInSeconds = 1.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){

        id strongSelf = weakSelf;

        if (!strongSelf) {
            return;
        }

        // Schedule the timer again
        timer();

        // Always use strongSelf when calling a method or accessing an iVar
        [strongSelf doSomething];
        strongSelf->anIVar = 0;
    });
};

// Start the timer for the first time
timer(); 

这样你将有一个计划任务,每秒都会被调用,它不会保留目标(自我),如果目标被解除分配,它将自行结束。

With this you will have a scheduled task that will be called at every sec, it will not retain the target (self) and it will end itself if the target is deallocated.

来源: NSTimer替代方案

这篇关于NSTimer的更好替代品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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