这里有点问题......我正在写一个ios应用程序(一个游戏),我需要它能够暂停自己。所以我认为最好的方法是在单独的线程中分离游戏执行,以便主线程可以根据需要简单地停止它。唯一的问题是:当你运行游戏时,会调用一个递归函数(通过以下方式完成递归)
[self performSelector: withObject: afterDelay:]
我不知道如何将递归方法隔离到新线程中。我试过了:
[NSThread detachNewThreadSelector:@selector(myThreadMainMethod:) toTarget:self withObject:nil];
但是它没有递归就执行(只是一次)......我想,如果我在方法结束时再次分离一个新线程,我就会陷入一堆独立的线程。帮助
答案 0 :(得分:0)
这是一种使用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