美文网首页Effective Objective-C 2.0
📚Effective OC - Tip 52: 别忘了NSTim

📚Effective OC - Tip 52: 别忘了NSTim

作者: 小万叔叔 | 来源:发表于2017-01-08 16:27 被阅读46次

Normal

  1. NSTimer 会导致持有目标对象,因为会很容易出现循环引用内存泄漏的问题。
  2. 解决方案
/** 
1. 在释放之前就执行invalidate, 显然这种场景很不适合也很不方便,就算在appear,disappear的时候配
对,也不一定适用于所有场景。
*/
[timer invalidate];
/**
2. 把不安全的 selector 转换为 block 或者 closure 的方式,用 weak 来解决循环引用的问题
显然 Apple 意识到了这个问题,在 iOS10 增加了一个 block 的方案
我们先来看一下系统的方法,scheduled 开头的方法都会加入到当前的runloop 的 defaultMode 模式中,
timerWith 开头的需要自己手动添加到runloop中。
*/
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block;  //iOS 10 only
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;   
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo; 
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
/** 
我们再来看看本书中的方法
1. 使用block 的方式来打破循环引用。
2. 我做了些许改动,如果是iOS10 上面则会调用系统的方法。
3. 由于iOS10 以下最终还是执行Selector 方法,所以对传入的block,默认情况下是分配在栈上的,在离开函数作用域要继续能够执行,需要拷贝到堆上面,所以需要执行block copy. 
4. 这样操作,由于Timer不再同外界vc相互强引用,所以不会导致vc不释放。
5. 但是是不是就没有问题了呢,因为timer不释放,所以要么在外界vc dealloc的时候invalidate, 要么,在block里面判断weak后释放。
*/
@implementation NSTimer (FPPBlockSupport)
//iOS系统的方法 scheduledTimerWithTimeInterval
+ (NSTimer *)fpp_scheduledTimerWithTimeInterval:(NSTimeInterval)intervel
                                        repeats:(BOOL)repeats
                                          block:(void (^)(NSTimer *))block {
    if ([[[UIDevice currentDevice]systemVersion]floatValue] > 10.0) {
        return [self scheduledTimerWithTimeInterval:intervel repeats:repeats block:block];
    }
    return [self scheduledTimerWithTimeInterval:intervel
                                         target:self
                                       selector:@selector(fpp_blockInvoke:)
                                       userInfo:[block copy]
                                        repeats:repeats];
}
+ (void)fpp_blockInvoke:(NSTimer *)timer {
    void (^block)(NSTimer *) = timer.userInfo;
    if (block) {
        block(timer);
    }
}
//调用的方式 Case1 || Case2
- (void)dealloc {
    NSLog(@"dealloc self");
      //case1: 主动释放
    [_timer invalidate];
    _timer = nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor redColor];
    __weak typeof(self) weakSelf = self;
    __block int count = 0;
    _timer = [NSTimer fpp_scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer *timer) {
        __strong typeof(weakSelf) __self = weakSelf;
        if (__self) {
            [__self timeEvent];
            count++;
        }
        else {
            NSLog(@"time is nil, still running");
            //case2:需要加上这样,全局的timer才不会不释放
          //[timer invalidate];
          //timer = nil;
        }
    }];
}
- (void)timeEvent {
    NSLog(@"time repeating");
}

Extension

  1. Runloop 接收timer source 的机制
    //套用 ibireme Runloop 文章里面的一张图,如有版权问题,请与我联系。

    2017010842513RunLoop_1.png
    这里先不讲Runloop相关的知识总结,仅仅说明一下timer 事件。
    从以上图可以知道 Timer是同Runloop挂钩的,如果不能被Runloop接收也就不能产生响应的事件处理。
    从我的认知范围里面, Timer 和 performSelector 应该在底层原理基本类似,而CADisplayLink 应该用了更为复杂的逻辑来实现。
  2. 其他Timer的使用方法

/*
 Normal
 1. NSTimer
 2. Dispatch timer
 3. CADisplayLink
 
 Delay
 1. preformSelector after
 2. dispath after
*/

//MARK: Normal
//Case NSTimer:
let timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { (timer) in
    print("timer repeating")
}
timer.invalidate()

//Case Dispatch timer:
let sourceTimer = DispatchSource.makeTimerSource()
sourceTimer.scheduleRepeating(deadline: DispatchTime.now(), interval: 3)
sourceTimer.setEventHandler { 
    print("sourceTimer repeating")
}
sourceTimer.resume()
sourceTimer.cancel()

//Case CADisplayLink:
//需要注意的是如果selector这种用法,是 OC 消息调度的机制,所以需要@objc来修饰,但由于
//其未知因素,也是不安全的,所以一般情况下应尽量避免使用。
//MARK: CADisplayLink
@objc func displayLinkShow() {
    print(" displayLink timer repeating")
}
func testCADisplayLink() {
    timer = CADisplayLink.init(target: self, selector: #selector(displayLinkShow))
    timer?.add(to: .main, forMode: .defaultRunLoopMode)
}

// MARK: Delay
// Case: preformSelector after
@objc func performShow() {
    print("do perform after")
}
func perform() {
    self.perform(#selector(performShow), with: nil, afterDelay: 3)
}

//Case dispath after: 
let dispatchQueue = DispatchQueue.init(label: "11")
dispatchQueue.asyncAfter(deadline: DispatchTime.now() + 1) {
    print("do GCD after")
}

相关文章

网友评论

    本文标题:📚Effective OC - Tip 52: 别忘了NSTim

    本文链接:https://www.haomeiwen.com/subject/adpfbttx.html