#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