iOS之-NSTimer防止循环引用

NSTimer

1. iOS 10 NSTimer 的新 API

iOS 10 之后,苹果为 NSTimer 添加了一个官方 API,支持传入 block 类型参数。

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)interval
                           repeats:(BOOL)repeats 
                             block:(void (^)(NSTimer *timer))block 
API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval
                                    repeats:(BOOL)repeats
                                  block:(void (^)(NSTimer *timer))block 
API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));

2. iOS 10之前,防止对 VC 的循环引用方案

  • 给 NSTimer 添加一个 category,新增传入 block 类型参数的接口
  • 分类实现是将此 block 作为 NSTimer 的 userInfo参数传入,而 NSTimer 的 target 则设置为 timer 自己。以此来避免 NSTimer 持有 VC
// NSTimer+BlocksSupport.h
#import 

@interface NSTimer (BlocksSupport)
+ (NSTimer *)ly_scheduledTimerWithTimeInterval:(NSTimeInterval)interval
repeats:(BOOL)repeats
block:(void(^)())block;
@end

// NSTimer+BlocksSupport.m
#import "NSTimer+BlocksSupport.h"

@implementation NSTimer (BlocksSupport)
+ (NSTimer *)ly_scheduledTimerWithTimeInterval:(NSTimeInterval)interval
                                       repeats:(BOOL)repeats
                                         block:(void(^)())block {

    return [self scheduledTimerWithTimeInterval:interval
                                         target:self
                                       selector:@selector(ly_blockInvoke:)
                                       userInfo:[block copy]
                                        repeats:repeats];
}

+ (void)ly_blockInvoke:(NSTimer *)timer {
    void (^block)() = timer.userInfo;
    if(block) {
        block();
    }
}

@end
  • reference

你可能感兴趣的:(iOS之-NSTimer防止循环引用)