平时咱们使用NSTimer
或者CADisplayLink
,若是不加处理直接使用系统提供的API方法,就有可能出现强引用问题(注意是强引用
非循环引用
)。php
场景: 控制器A -> push -> 控制器B,控制器B的实现以下:objective-c
#import "ViewControllerB.h"
@interface ViewController ()
@property (strong, nonatomic) NSTimer *timer;
@end
@implementation ViewControllerB
- (void)viewDidLoad {
[super viewDidLoad];
//每隔一秒钟调用一次timerTest
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTest) userInfo:nil repeats:YES];
}
- (void)timerTest
{
NSLog(@"%s", __func__);
}
- (void)dealloc
{
NSLog(@"%s", __func__);
[self.timer invalidate];
}
@end
复制代码
由控制器A进入控制器B, 定时器开始工做,但当点击返回, 由B页面返回A页面时,会发现控制器B
的dealloc
方法没有调用,说明控制器B
并无销毁。markdown
那么这是为何呢??? 是由于循环引用问题 ??,嗯,看着像,由于控制器B
强引用timer
,timer
建立时会对target
(即控制器B
) 产生强引用,从而产生了强引用。网上不少文章也是这么解释的,其实也不能算错,由于目前来看确实是有循环引用。 可是当你把控制器B
对timer
的引用改成弱引用
即:async
@property (weak, nonatomic) NSTimer *timer;
复制代码
你会惊奇的发现,前面的问题依旧存在。那么这又是为何呢????,理应来讲, 控制器B
弱引用timer
,那么当- (void)viewDidLoad
方法执行完,timer的做用域就结束了,应该挂掉才对, 事实上却没有,说明应该有别的对象强引用着timer
。事实如此,这个别的对象
其实就是Runloop对象。有源码为证(参考自GNUStep):函数
+ (NSTimer*) scheduledTimerWithTimeInterval: (NSTimeInterval)ti
target: (id)object
selector: (SEL)selector
userInfo: (id)info
repeats: (BOOL)f
{
id t = [[self alloc] initWithFireDate: nil
interval: ti
target: object // timer会强引用object
selector: selector
userInfo: info
repeats: f];
[[NSRunLoop currentRunLoop] addTimer: t forMode: NSDefaultRunLoopMode];
RELEASE(t);
return t;
}
复制代码
能够看到,timer
建立以后是直接加入到了当前的Runloop
中,由此可得:控制器B
、timer
、Runloop
之间的引用关系:Runloop
=> timer
=> 控制器B
。 因此 控制器B
销毁不了的缘由实际上是timer
对它存在强引用。oop
那么如何解决呢?其实只要将timer
对控制器B
的引用改成弱引用便可,具体的方案其实网上均可以找到, 这里也简单说一下:ui
方案一: 换方法,使用block
的方式实现。(简单明了) 实现以下:atom
#import "ViewController.h"
@interface ViewController ()
@property (strong, nonatomic) NSTimer *timer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 使用block方式,实现timer对vc的弱引用
__weak typeof(self) weakSelf = self;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
[weakSelf timerTest];
}];
}
- (void)timerTest
{
NSLog(@"%s", __func__);
}
- (void)dealloc
{
NSLog(@"%s", __func__);
[self.timer invalidate];
}
@end
复制代码
方案二: 增长一个代理对象。以下: spa
实现代码:代理
@interface MJProxy : NSProxy
+ (instancetype)proxyWithTarget:(id)target;
@property (weak, nonatomic) id target;
@end
#import "MJProxy.h"
@implementation MJProxy
+ (instancetype)proxyWithTarget:(id)target
{
// NSProxy对象不须要调用init,由于它原本就没有init方法
MJProxy *proxy = [MJProxy alloc];
proxy.target = target;
return proxy;
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
return [self.target methodSignatureForSelector:sel];
}
- (void)forwardInvocation:(NSInvocation *)invocation
{
[invocation invokeWithTarget:self.target];
}
@end
#import "ViewController.h"
#import "MJProxy.h"
@interface ViewController ()
@property (strong, nonatomic) NSTimer *timer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[MJProxy proxyWithTarget:self] selector:@selector(timerTest) userInfo:nil repeats:YES];
}
- (void)timerTest
{
NSLog(@"%s", __func__);
}
- (void)dealloc
{
NSLog(@"%s", __func__);
[self.timer invalidate];
}
@end
复制代码
CADisplayLink 的使用也是同样的。
#import "ViewController.h"
#import "MJProxy.h"
@interface ViewController ()
@property (strong, nonatomic) CADisplayLink *link;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 保证调用频率和屏幕的刷帧频率一致,60FPS
self.link = [CADisplayLink displayLinkWithTarget:[MJProxy proxyWithTarget:self] selector:@selector(linkTest)];
[self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}
- (void)timerTest
{
NSLog(@"%s", __func__);
}
- (void)linkTest
{
NSLog(@"%s", __func__);
}
- (void)dealloc
{
NSLog(@"%s", __func__);
[self.link invalidate];
}
@end
复制代码
NSTimer
定时器是是偏差的,缘由与Runloop
有关。 NSTimer
依赖于Runloop
,NSTimer
建立以后须要加入到Runloop
中,而后Runloop
每次循环都会检查一下NSTimer
,看是否须要执行相应的任务。 可是Runloop
的每一次循环所花费的时间是不固定的,任务较多,时间可能就长一点,任务少,时间可能就短一些。这是形成NSTimer
有偏差的缘由。
一句话: NSTimer依赖于RunLoop,若是RunLoop的任务过于繁重,可能会致使NSTimer不许时
那iOS中如何才能准确的计时呢? 可使用GCD定时器(与Runloop没啥关系,直接调用内核函数)。
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) dispatch_source_t timer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 建立串行队列
dispatch_queue_t queue = dispatch_queue_create("com.long", DISPATCH_QUEUE_SERIAL);
// 建立定时器
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
// 设置时间
uint64_t start = 2; // 2秒后开始
uint64_t interval = 1; // 间隔1秒
dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, start * NSEC_PER_SEC), interval * NSEC_PER_SEC, 0);
// 设置事件回调
dispatch_source_set_event_handler(timer, ^{
NSLog(@"11111111"); // 须要执行的任务
});
// 也能够这样设定
// dispatch_source_set_event_handler_f(timer, fireTimer);
// 启动定时器
dispatch_resume(timer);
self.timer = timer; // 保住timer的命
}
void fireTimer() {
NSLog(@"11111111"); // 须要执行的任务
}
@end
复制代码
为了方便之后使用,下面将GCD的定时器进行一下封装。
.h文件
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface LCTimer : NSObject
+ (NSString *) execTask:(void(^)(void))task
start:(NSTimeInterval)start
interval:(NSTimeInterval)interval
repeating:(BOOL)repeating
async:(BOOL)async;
+ (NSString *) execTask:(id)target
selector:(SEL)selector
start:(NSTimeInterval)start
interval:(NSTimeInterval)interval
repeating:(BOOL)repeating
async:(BOOL)async;
+ (void)cancelTask:(NSString *)task;
@end
NS_ASSUME_NONNULL_END
复制代码
.m文件
#import "LCTimer.h"
static NSMutableDictionary *timerMap_;
static dispatch_semaphore_t semaphore_;
@implementation LCTimer
// 类第一次接收到消息时调用
+ (void)initialize {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
timerMap_ = [[NSMutableDictionary alloc] init];
semaphore_ = dispatch_semaphore_create(1);
});
}
+ (NSString *)execTask:(void(^)(void))task start:(NSTimeInterval)start interval:(NSTimeInterval)interval repeating:(BOOL)repeating async:(BOOL)async {
if (!task || start < 0 || (repeating && interval <= 0)) return nil;
// 建立串行队列
dispatch_queue_t queue = async ? dispatch_get_global_queue(0, 0) : dispatch_get_main_queue();
// 建立定时器
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
// 设置时间
dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, start * NSEC_PER_SEC), interval * NSEC_PER_SEC, 0);
dispatch_semaphore_wait(semaphore_, DISPATCH_TIME_FOREVER);
// 任务的Id
NSString *taskId = [NSString stringWithFormat:@"%zd", timerMap_.count];
[timerMap_ setObject:timer forKey:taskId];
dispatch_semaphore_signal(semaphore_);
// 设置事件回调
dispatch_source_set_event_handler(timer, ^{
task();
if (!repeating) {
[self cancelTask:taskId];
}
});
// 启动定时器
dispatch_resume(timer);
return taskId;
}
+ (NSString *)execTask:(id)target selector:(SEL)selector start:(NSTimeInterval)start interval:(NSTimeInterval)interval repeating:(BOOL)repeating async:(BOOL)async {
if (!target || !selector) return nil;
return [self execTask:^{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
if ([target respondsToSelector:selector]) {
[target performSelector:selector];
}
#pragma clang diagnostic push
} start:start interval:interval repeating:repeating async:async];
}
+ (void)cancelTask:(NSString *)task {
if (task.length <= 0) return;
dispatch_semaphore_wait(semaphore_, DISPATCH_TIME_FOREVER);
dispatch_source_t timer = [timerMap_ objectForKey:task];
if (timer) {
dispatch_source_cancel(timer);
[timerMap_ removeObjectForKey:task];
}
dispatch_semaphore_signal(semaphore_);
}
@end
复制代码
简单使用:
#import "ViewController.h"
#import "LCTimer.h"
@interface ViewController ()
@property (nonatomic, strong) dispatch_source_t timer;
@property (nonatomic, strong) NSString *taskId;
@property (nonatomic, strong) NSString *taskId2;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.taskId = [LCTimer execTask:^{
NSLog(@"222222 %@", [NSThread currentThread]);
} start:2 interval:1 repeating:YES async:NO];
self.taskId2 = [LCTimer execTask:self selector:@selector(justForTest) start:2 interval:1 repeating:YES async:YES];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[LCTimer cancelTask:self.taskId];
[LCTimer cancelTask:self.taskId2];
}
- (void)justForTest {
NSLog(@"555555555");
}
@end
复制代码