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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容