在ios10以前苞轿,使用NSTimer的
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
會(huì)導(dǎo)致self被timer持有耍铜,如果timer不主動(dòng)調(diào)用invalidate越妈,或者invalidate放在dealloc里面错沃,會(huì)產(chǎn)出保留環(huán),導(dǎo)致內(nèi)存泄露
在10以后雀瓢,我們可以調(diào)用
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block
放心的把invalidate寫在dealloc里面(當(dāng)然block中引用self需要weak - strong一下)
10之前應(yīng)該怎么辦呢枢析?我們可以仿寫系統(tǒng)的這個(gè)方法,用分類的方式加入:
.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