iOS之-NSTimer防止循环引用

2018-05-07  本文已影响23人  Jacob_LJ
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+BlocksSupport.h
#import <Foundation/Foundation.h>

@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
上一篇下一篇

猜你喜欢

热点阅读