這是一種方法來啓動/停止定期做的工作使用GCD:
typedef void (^loop_work_t)(void);
@interface Loop : NSObject
@property (nonatomic,assign) loop_work_t block;
@property (nonatomic,assign) NSTimeInterval interval;
@property (nonatomic,assign) dispatch_source_t timerSource;
-(id) initWithInterval:(NSTimeInterval)seconds block:(loop_work_t)block;
-(void) start;
-(void) stop;
@end
#import "Loop.h"
@implementation Loop
@synthesize interval=_interval;
@synthesize block=_block;
@synthesize timerSource=_timerSource;
-(id) initWithInterval:(NSTimeInterval)seconds block:(loop_work_t)block
{
if (self = [super init]){
self.interval = seconds;
self.block = block;
dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, backgroundQueue);
dispatch_source_set_timer(timerSource, dispatch_time(DISPATCH_TIME_NOW, 0), seconds*NSEC_PER_SEC, 0*NSEC_PER_SEC);
dispatch_source_set_event_handler(timerSource, ^{
block();
});
self.timerSource = timerSource;
}
return self;
}
-(void) start {
dispatch_resume(self.timerSource);
}
-(void) stop {
dispatch_suspend(self.timerSource);
}
@end
用法:
id __weak weakSelf = self;
Loop *loop = [[Loop alloc]initWithInterval:5 block:^{
// this will run every 5 seconds
[weakSelf someMethodOfYourClassDoingUsefulWork];
}];
複製粘貼此最後一個塊的任何地方,巢幾個循環,如果你需要。你可以開始/你不停的循環參考停止長:
[loop start]; // start the loop
[loop stop]; // stop the loop
哦,還有一兩件事:如何同時循環不回採它運行我改變遞歸區間? (例如,我正在執行的代碼塊需要能夠加速自己。) – user1508829 2012-08-08 13:26:29
保存對timerSource的引用,然後將dispatch_source_set_timer行復制粘貼到具有不同'seconds'參數的單獨方法。只是執行該行將改變間隔。 – Jano 2012-08-08 13:36:15