NSTimer的使用

NSTimer的基础用法以及程序挂起后NSTimer仍然可以在后台运行计时

1. 关于NSTimer一些基本的知识,网上应该有很多讲解,废话不多少,直接上代码

(1) 下面是简单的实现代码

#import "NSTimerController.h"

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
static const NSInteger button_tag = 100;

@interface NSTimerController ()

@property (nonatomic,strong) NSTimer* timer; /*定时器*/
@property (nonatomic,assign) NSInteger secondsCountDown; /*倒计时的时间数*/
@property (nonatomic,strong) UIButton* count_button; /*点击的按钮*/
@property (nonatomic,assign) NSInteger space; /*宽度*/
@property (nonatomic,assign) BOOL isClick; /*防止连续点击*/

@end

@implementation NSTimerController

- (void)viewDidLoad
{
    [super viewDidLoad];
    _secondsCountDown = 20; /*初使时间20秒*/
    _space = 300; /*按钮的宽度*/
    [self count_button];
}

-(void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_timer invalidate]; /*将定时器从运行循环中移除*/
    _timer = nil; /*销毁定时器, 这样可以避免控制器不死*/
}

-(UIButton*) count_button
{
    if (!_count_button)
    {
        _count_button = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.view addSubview:_count_button];
        _count_button.frame = CGRectMake(SCREEN_WIDTH / 2 - 150, SCREEN_HEIGHT - 300, _space, 40);
        _count_button.tag = button_tag;
        _count_button.layer.cornerRadius = 5;
        [_count_button setTitle:@"重新获取" forState:UIControlStateNormal];
        _count_button.backgroundColor = [UIColor orangeColor];
        [_count_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_count_button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _count_button;
}

-(void) buttonAction:(UIButton*) sender
{
    if (!_isClick)
    {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];

        /*注意点:
         将计数器的repeats设置为YES的时候,self的引用计数会加1。
         因此可能会导致self(即viewController)不能release。
         所以,必须在viewWillAppear的时候,将计数器timer停止,否则可能会导致内存泄露。*/
        
        /*手动启动Runloop,然后使其在线程池里运行*/
        /* 
         1: 下面这个方法切忌不要轻易使用,避免网络请求的线程会被杀死:[[NSRunLoop currentRunLoop] run];

         2: 如果想用,建议如下操作:
         // dispatch_async(dispatch_get_global_queue(0, 0), ^{
         //  _countDownTimer = [NSTimer  scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
         // [[NSRunLoop currentRunLoop] run];
                    });
          */

        //正确用法:
         [[NSRunLoop currentRunLoop] addTimer:_timer  forMode:NSRunLoopCommonModes];
    }
}

-(void) timeFireMethod
{
    _isClick = YES;
    _secondsCountDown--;
    [_count_button setTitle:[NSString stringWithFormat:@"重新获取 (%ld)",(long)_secondsCountDown] forState:UIControlStateNormal];
    [_count_button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    NSLog(@"_secondsCountDown:%ld",(long)_secondsCountDown);
    if (_secondsCountDown <= 0)
    {
        _isClick = NO;
        [_timer invalidate];
        _secondsCountDown = 20;
        [_count_button setTitle:@"重新获取" forState:UIControlStateNormal];
        [_count_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }
}

@end

下面两张图是简易的效果图:

图1.png

图2.png

(2) 上面的代码中,有关于一些细节的说明,但是还有一些其他的重点细节,在下面说下

在页面即将消失的时候关闭定时器,之后等页面再次打开的时候,又开启定时器(只要是防止它在后台运行,暂用CPU)

-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    /*开启继续运行NSTimer*/
    [_timer setFireDate:[NSDate distantPast]];
}

-(void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    /*关闭NSTimer*/
    [_timer setFireDate:[NSDate distantFuture]];
}


2. 程序挂起后NSTimer仍然可以在后台运行计时

具体操作如下:

步骤一: 在info里面如下设置:
info -->添加 Required background modes -->设置 App plays audio or streams audio/video using AirPlay

3C1F3F3C-6860-4A29-84C1-65554EFDF687.png

步骤二:在AppDelegate.m里面调用

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    /*定时器后台运行*/
    NSError *setCategoryErr = nil;
    NSError *activationErr  = nil;
    /*设置Audio Session的Category 一般会在激活之前设置好Category和mode。但是也可以在已激活的audio session中设置,不过会在发生route change之后才会发生改变*/
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryErr];
    /*激活Audio Session*/
    [[AVAudioSession sharedInstance] setActive: YES error: &activationErr];
 }

/*
 通过UIBackgroundTaskIdentifier可以实现有限时间内在后台运行程序
 程序进入后台时调用applicationDidEnterBackground函数,
 */
- (void)applicationDidEnterBackground:(UIApplication *)application{
    
    UIApplication* app = [UIApplication sharedApplication];
    __block UIBackgroundTaskIdentifier bgTask;
    
    /*注册一个后台任务,告诉系统我们需要向系统借一些事件*/
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                /*销毁后台任务标识符*/
                /*不管有没有完成,结束background_task任务*/
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    }];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                /*销毁后台任务标识符*/
                /*不管有没有完成,结束background_task任务*/
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    });
}

参考如下链接知识,深表感谢:

IOS音频播放学习参考
IOS后台挂起时运行程序UIBackgroundTaskIdentifier

UITableView滚动时NSTimer不执行

2016年07月06日 01:59:08 gx_wqm 阅读数:656

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/gx_wqm/article/details/51835775

解决方法增加timer的runloop模式:

[[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode]; 或
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

原因分析:

NSTImer的实现时基于runLoop的,而runloop又有以下5种模式,某一时刻只能处理对应模式下的事件。

  • Default模式
    定义:NSDefaultRunLoopMode (Cocoa) kCFRunLoopDefaultMode (Core Foundation)
    描述:默认模式中几乎包含了所有输入源(NSConnection除外),一般情况下应使用此模式。
  • Connection模式
    定义:NSConnectionReplyMode(Cocoa)
    描述:处理NSConnection对象相关事件,系统内部使用,用户基本不会使用。
  • Modal模式
    定义:NSModalPanelRunLoopMode(Cocoa)
    描述:处理modal panels事件。
  • Event tracking模式
    定义:

    UITrackingRunLoopMode

    (iOS) NSEventTrackingRunLoopMode(cocoa)
    描述:在拖动loop或其他user interface tracking loops时处于此种模式下,在此模式下会限制输入事件的处理。例如,当手指按住UITableView拖动时就会处于此模式。
  • Common模式
    定义:NSRunLoopCommonModes (Cocoa) kCFRunLoopCommonModes (Core Foundation)
    描述:这是一个伪模式,其为一组run loop mode的集合,将输入源加入此模式意味着在Common Modes中包含的所有模式下都可以处理。在Cocoa应用程序中,默认情况下Common Modes包含default modes,modal modes,event Tracking modes.可使用CFRunLoopAddCommonMode方法想Common Modes中添加自定义modes。

获取当前线程的run loop mode:

NSString* runLoopMode = [[NSRunLoopcurrentRunLoop]currentMode];

NSTimer默认处于NSDefaultRunLoopMode,在没有滚动时,runloop处于NSDefaultRunLoopMode下,滚动时处于UITrackingRunLoopMode,导      致NSTimer事件源被过滤了,所以不执行,那怎么办,只需要给NSTimer再添加一个模式:

[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode]或

干脆就所有模式下都能执行:

[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

IOS中定时器NSTimer的开启与关闭

调用一次计时器方法:

myTimer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(scrollTimer) userInfo:nil repeats:NO];

  1. //不重复,只调用一次。timer运行一次就会自动停止运行

  2. 重复调用计时器方法

  3. timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(function:) userInfo:nil repeats:YES];

  4. //每1秒运行一次function方法。

注意:将计数器的repeats设置为YES的时候,self的引用计数会加1。因此可能会导致self(即viewController)不能release,所以,必须在viewDidDisappear的时候,将计数器timer停止,否则可能会导致内存泄露。

停止timer的运行,但这个是永久的停止:(注意:停止后,一定要将timer赋空,否则还是没有释放。不信?你自己试试~)

  1. //取消定时器

  2. [timer invalidate];

  3. timer = nil;

  4. 要想实现:先停止,然后再某种情况下再次开启运行timer,可以使用下面的方法:

首先关闭定时器不能使用上面的方法,应该使用下面的方法:

  1. //关闭定时器

  2. [myTimer setFireDate:[NSDate distantFuture]];


然后就可以使用下面的方法再此开启这个timer了:

  1. //开启定时器

  2. [myTimer setFireDate:[NSDate distantPast]];


例子:比如,在页面消失的时候关闭定时器,然后等页面再次打开的时候,又开启定时器。

(主要是为了防止它在后台运行,暂用CPU)可以使用下面的代码实现:

  1. //页面将要进入前台,开启定时器

  2. -(void)viewWillAppear:(BOOL)animated

  3. {

  4. //开启定时器

  5. [scrollView.myTimer setFireDate:[NSDate distantPast]];

  6. }

  7.  
  8. //页面消失,进入后台不显示该页面,关闭定时器

  9. -(void)viewDidDisappear:(BOOL)animated

  10. {

  11. //关闭定时器

  12. [scrollView.myTimer setFireDate:[NSDate distantFuture]];

  13. }


OK,搞定。

猜你喜欢

转载自blog.csdn.net/u011862058/article/details/84521164