这是一种使用 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