#import <Foundation/Foundation.h> @interface EocClass : NSObject -(void)startPolling; -(void)stopPolling; @end #import "EocClass.h" #import "NSTimer+EOCBlockSupport.h" @implementation EocClass { NSTimer *_pollTimer; } -(id)init{ return [super init]; } -(void)startPolling{ //目標self 和實例變量_pollTimer 產生保留環 _pollTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(P_doPoll) userInfo:nil repeats:YES]; //分類解決 保留環問題 __weak EocClass *weakSelf = self; _pollTimer = [NSTimer eoc_scheduledTimerWithTimerInterval:5.0 block:^{ [self P_doPoll]; } repeats:YES]; } -(void)stopPolling { [_pollTimer invalidate]; _pollTimer = nil; } -(void)dealloc{ [_pollTimer invalidate]; } -(void)P_doPoll{ //do some thing; } @end
#import <Foundation/Foundation.h> //添加塊在NSTimer分類中,解決保留環的問題 @interface NSTimer (EOCBlockSupport) +(NSTimer *)eoc_scheduledTimerWithTimerInterval:(NSTimeInterval)interval block:(void(^)())block repeats:(BOOL)repeats; @end #import "NSTimer+EOCBlockSupport.h" @implementation NSTimer (EOCBlockSupport) +(NSTimer *)eoc_scheduledTimerWithTimerInterval:(NSTimeInterval)interval block:(void (^)())block repeats:(BOOL)repeats{ return [self scheduledTimerWithTimeInterval:interval target:self selector:@selector(eoc_blockInvoke:) userInfo:[block copy] repeats:repeats]; } +(void)eoc_blockInvoke:(NSTimer *)timer{ void (^block)() = timer.userInfo; if (block){ block(); } } @end