Dev*_*shi 2 cocoa nsthread nsoperationqueue grand-central-dispatch
我有一个应用程序,我在后台重复调用方法.我通过以下步骤实现了这一点:
以下是我使用的代码:
- (void) applicationDidFinishLaunching:(NSNotification *)notification
[NSApplication detachDrawingThread:@selector(refreshUserIdPassword) toTarget:self withObject:nil];
}
-(void)refreshUserIdPassword
{
[self getAllUserIdsPasswordsContinousely];
[NSThread sleepForTimeInterval:180];
[self refreshUserIdPassword];
}
Run Code Online (Sandbox Code Playgroud)
我已经读过NSThread不是执行后台任务的最佳方法,并且在cocoa中提供了其他类,例如 - NSOperationQueue和GCD,它应优先于NSThread来执行异步任务.所以我试图使用替代类来实现上面指定的功能.
问题是 - 虽然我能够使用这些类执行异步任务,但我无法使用这些类执行重复性任务(如我的情况).
有人可以对此有所了解并引导我走向正确的方向吗?
我想你会使用你发布的代码获得堆栈溢出(没有双关语).-refreshUserIdPassword
无限地递归......
使用GCD怎么样?
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Insert code here to initialize your application
dispatch_source_t timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
dispatch_source_set_timer(timerSource, dispatch_time(DISPATCH_TIME_NOW, 0), 180*NSEC_PER_SEC, 10*NSEC_PER_SEC);
dispatch_source_set_event_handler(timerSource, ^{
[self getAllUserIdsPasswordsContinuously];
});
dispatch_resume(timerSource);
self.timer = timerSource;
}
Run Code Online (Sandbox Code Playgroud)