创建NSTimer有下面三中方式
A timer object can be registered in only one run loop at a time, although it can be added to multiple run loop modes within that run loop. There are three ways to create a timer:
-
Use the
scheduledTimerWithTimeInterval:invocation:repeats:
orscheduledTimerWithTimeInterval:target:selector:userInfo:repeats:
class method to create the timer and schedule it on the current run loop in the default mode. -
Use the
timerWithTimeInterval:invocation:repeats:
ortimerWithTimeInterval:target:selector:userInfo:repeats:
class method to create the timer object without scheduling it on a run loop. (After creating it, you must add the timer to a run loop manually by calling theaddTimer:forMode:
method of the correspondingNSRunLoop
object.) -
Allocate the timer and initialize it using the
initWithFireDate:interval:target:selector:userInfo:repeats:
method. (After creating it, you must add the timer to a run loop manually by calling theaddTimer:forMode:
method of the correspondingNSRunLoop
object.)
- @interface NSTimer (EOCBlocksSupport)
- + (NSTimer *)eoc_scheduledTimerWithTimeInterval:(NSTimeInterval)interval
- block:(void(^)())block
- repeats:(BOOL)repeats;
- @end
- @implementation NSTimer (EOCBlocksSupport)
- + (NSTimer *)eoc_scheduledTimerWithTimeInterval:(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();
- }
- }
-
-(void)startPolling {__weak EOCClass * weakself = self;_pollTimer = eoc_scheduledTimerWithTimeInterval:5.0
- block:^ {
- EOCClass *strongSelf = weakself;
- //上边代码也可以用__strong来修饰强关系,这里面应该是变为autoReleaseing的了。可以保证在这个作用于范围使用。
- [strongSelf doReFresh];
- }
- repeats:(BOOL)YES;
- }