在单独的线程中分离递归方法 - Objective-C



这里有点问题...我正在编写一个ios应用程序(游戏),我需要它能够自行暂停。所以我认为最好的方法是将游戏执行分离到一个单独的线程中,以便主线程可以根据需要简单地停止它。唯一的问题是:当你运行游戏时,会调用一个递归函数(递归完成者:)

[self performSelector: withObject: afterDelay:]

而且我不知道如何将递归方法隔离到新线程中。我试过:

[NSThread detachNewThreadSelector:@selector(myThreadMainMethod:) toTarget:self withObject:nil];

但它在没有递归的情况下执行(只有一次)...我想,如果我在方法结束时再次分离一个新线程,我只会被一堆单独的线程卡住。

以下是使用 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

最新更新