NSTimer+Block

在ios10以前,使用NSTimer的

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;

会导致self被timer持有,如果timer不主动调用invalidate,或者invalidate放在dealloc里面,会产出保留环,导致内存泄露

在10以后,我们可以调用

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block

放心的把invalidate写在dealloc里面(当然block中引用self需要weak - strong一下)

10之前应该怎么办呢?我们可以仿写系统的这个方法,用分类的方式加入:
.h

#import <Foundation/Foundation.h>

@interface NSTimer (Block)
+ (NSTimer *)Block_ScheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block;
@end

.m

#import "NSTimer+Block.h"

@implementation NSTimer (Block)

+ (NSTimer *)Block_ScheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block{
    return [self scheduledTimerWithTimeInterval:interval target:self selector:@selector(Block_BlockInvoke:) userInfo:[block copy] repeats:repeats];
}

+ (void)Block_BlockInvoke:(NSTimer *)timer{
    void(^block)(NSTimer *timer) = timer.userInfo;
    !block?:block(timer);
}
@end

推荐阅读更多精彩内容