iOS定时器相关实践

NSTimer定时器

在iOS中,NSTimer是咱们日常都会用到的定时器。因此咱们有必要了解其相关的使用方法和须要注意的点。在咱们建立NSTimer定时器是timer是强引用target的这样就造成了循环引用的问题,从而致使内存泄漏。要避免这样的问题咱们可使用一下方法:ios

  1. 在合适的地方销毁NSTimer 在咱们离开当前视图时,咱们能够在- (void)didMoveToParentViewController:(UIViewController *)parent中销毁timer
- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"======== ViewController1 将要加载视图: viewDidLoad =======\n");
    //iOS10
//    self.timer = [NSTimer timerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
//
//    }];
    self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(changeTime) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
}

- (void)changeTime {
    
}

- (void)didMoveToParentViewController:(UIViewController *)parent {
    if (!parent) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)dealloc {
    NSLog(@"======== ViewController1 释放: dealloc =======\n");
}

复制代码
  1. 使用block方式添加target-actionNSTimer分类添加方法以下:
+ (NSTimer *)S_timerWithTimeInterval:(NSTimeInterval)ti block:(void(^)(void))block userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo {
    return [self timerWithTimeInterval:ti target:self selector:@selector(blockSelector:) userInfo:[block copy] repeats:yesOrNo];
}

+ (void)blockSelector:(NSTimer *)timer {
    void(^block)(void) = timer.userInfo;
    if (block) {
        block();
    }
}
复制代码

调用bash

__weak typeof(self) weakSelf = self;
    self.timer = [NSTimer S_timerWithTimeInterval:1 block:^{
        [weakSelf changeTime];
    } userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
}

- (void)changeTime {
    
}
复制代码

经过block的方式将action传递出来,实际上timer的target是NSTimer类。即这样就不会产生循环引用。使用中因为使用了block因此要注意其引发的循环引用。 3. 定义中介继承NSProxy进行消息转发,消除强引用 关于NSProxy类的有关知识能够看连接的资料,这里就再也不复述了。async

@property (nonatomic, weak) id target;

+ (instancetype)proxyWithWeakTarget:(id)target;

- (id)initWithTarget:(id)target;

@end

@implementation SProxy

+ (instancetype)proxyWithWeakTarget:(id)target {
    return [[SProxy alloc] initWithTarget:target];
}

- (id)initWithTarget:(id)target {
    _target = target;
    return self;
}

///将方法的签名(SEL)转发给真正实现了该消息的对象
- (void)forwardInvocation:(NSInvocation *)invocation {
    if ([_target respondsToSelector:invocation.selector]) {
        [invocation invokeWithTarget:_target];
    }
}

///为另外一个类实现的消息建立一个有效的方法签名
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
    return [_target methodSignatureForSelector:sel];
}

@end
复制代码
  1. 定义中介值继承自NSObject进行消息转发消除强引用
@interface TimerTraget : NSObject
@property (nonatomic, weak) id target;

+ (instancetype)timerTragetWithTarget:(id)target;

@end

+ (instancetype)timerTragetWithTarget:(id)target {
    TimerTraget *timer = [[TimerTraget alloc] init];
    timer.target = target;
    return timer;
}

- (id)forwardingTargetForSelector:(SEL)aSelector {
    if ([self.target respondsToSelector:aSelector]) {
        return self.target;
    }
    return nil;
}
///使用方法以下
    self.timer = [NSTimer timerWithTimeInterval:1 target:[TimerTraget timerTragetWithTarget:self] selector:@selector(changeTime) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
}

- (void)changeTime {
    
}
复制代码

GCD定时器

在咱们的平时开发中常常会用到定时器 ,相对于NSTimer实现的定时器,GCD定时器记录的时间相对要精确一些。并且不用考虑内存释放的问题。ide

如下是GCD实现基本的获取验证码的倒计时功能 直接上代码了oop

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.but = [[UIButton alloc] initWithFrame:CGRectMake(self.view.center.x, self.view.center.y, 100, 50)];
//    self.but.backgroundColor = [UIColor redColor];
    [self.but setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [self.but setTitle:@"获取验证码" forState:UIControlStateNormal];
    self.but.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.but addTarget:self action:@selector(tapClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.but];
}

- (void)tapClick:(UIButton*)but{

    [self playGCDTimer];
}

- (void)playGCDTimer{
    
    __block NSInteger time = 59;
    //全局队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    //建立timer 类型的定时器 (DISPATCH_SOURCE_TYPE_TIMER)
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);

    //设置定时器的各类属性(什么时候开始,间隔多久执行)
    // GCD 的时间参数通常为纳秒 (1 秒 = 10 的 9 次方 纳秒)
    // 指定定时器开始的时间和间隔的时间
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    
    //任务回调
    dispatch_source_set_event_handler(timer, ^{
        
        if (time <= 0) {
            
            dispatch_source_cancel(timer);//关闭定时器
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.but setTitle:@"从新发送" forState:UIControlStateNormal];
                self.but.userInteractionEnabled = YES;
                
            });
        }else{
            
            int seconds = time % 60;
            dispatch_sync(dispatch_get_main_queue(), ^{
               
                [self.but setTitle:[NSString stringWithFormat:@"从新发送(%.2d)",seconds] forState:UIControlStateNormal];
                self.but.userInteractionEnabled = NO;//验证码获取时禁止用户点击
            });
        }
        time--;
    });
    
    // 开始定时器任务(定时器默认开始是暂停的,须要复位开启)
    dispatch_resume(timer);
}
复制代码

好了GCD建立定时器的基本方法就介绍完了ui

相关文章
相关标签/搜索