04.Timer优化
前言
一、 NSTimer 常规使用
#import "NSTimerViewController.h"
@interface NSTimerViewController ()
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger count;
@end
@implementation NSTimerViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self selfTargetTimer];
}
#pragma mark - 不同 NSTimer 使用方式
/// 常规使用 self 作为 Target 的 NSTimer
- (void)selfTargetTimer {
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countAction) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
#pragma mark - Action
- (void)countAction {
self.count += 1;
NSLog(@"%@ - %ld",self, self.count);
}
- (void)dealloc {
[self.timer invalidate];
self.timer = nil;
NSLog(@"NSTimerViewController dealloc");
}
@end


1.1 weakSelf

1.2 block

二、 自定义 Timer
2.1 加一层间接

2.2 消息转发机制

Last updated