Objective-C:阻塞线程直到 NSTimer 完成(iOS)

标签 objective-c multithreading xcode ios nsthread

我一直在寻找并尝试为自己编程,以找到这个问题的答案。

我的 mainView Controller 内运行着一个辅助线程,然后它运行一个倒数至 0 的计时器。

当此计时器正在运行时,启动计时器的辅助线程应该暂停/阻止。

当计时器达到 0 时,辅助线程应该继续。

我已经尝试过 NSCondition 和 NSConditionLock 但没有效果,所以理想情况下我喜欢用代码解决我的问题的解决方案,或者为我指出如何解决这个问题的指南。不是简单地声明“使用 X”的内容。

- (void)bettingInit {    
    bettingThread = [[NSThread alloc] initWithTarget:self selector:@selector(betting) object:nil];
    [bettingThread start];
}

- (void)betting {

    NSLog(@"betting Started");
    for (int x = 0; x < [dealerNormalise count]; x++){
        NSNumber *currSeat = [dealerNormalise objectAtIndex:x];
        int currSeatint = [currSeat intValue];
        NSString *currPlayerAction = [self getSeatInfo:currSeatint objectName:@"PlayerAction"];
        if (currPlayerAction != @"FOLD"){
            if (currPlayerAction == @"NULL"){                
                [inactivitySeconds removeAllObjects];
                NSNumber *inactivitySecondsNumber = [NSNumber numberWithInt:10];
                runLoop = [NSRunLoop currentRunLoop];
                betLooper = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(betLoop) userInfo:nil repeats:YES];
                [runLoop addTimer:[betLooper retain] forMode:NSDefaultRunLoopMode];
                [runLoop run];

                // This Thread needs to pause here, and wait for some input from the other thread, then continue on through the for loop

                NSLog(@"Test");
            }
        }
    }
}

- (void)threadKiller {
    [betLooper invalidate];

    //The input telling the thread to continue can alternatively come from here
    return;
}

- (void)betLoop {
    NSLog(@"BetLoop Started");
    NSNumber *currentSeconds = [inactivitySeconds objectAtIndex:0];
    int currentSecondsint = [currentSeconds intValue];
    int newSecondsint = currentSecondsint - 1;
    NSNumber *newSeconds = [NSNumber numberWithInt:newSecondsint];
    [inactivitySeconds replaceObjectAtIndex:0 withObject:newSeconds];
    inacTimer.text = [NSString stringWithFormat:@"Time: %d",newSecondsint];                      

    if (newSecondsint == 0){

        [self performSelector:@selector(threadKiller) onThread:bettingThread  withObject:nil waitUntilDone:NO];

        // The input going to the thread to continue should ideally come from here, or within the threadKiller void above
    }
}

最佳答案

您不能在线程上运行计时器并同时使线程休眠。您可能需要重新考虑是否需要线程。

这里有一些事情需要指出。首先,当您安排计时器时:

betLooper = [NSTimer scheduledTimerWithTimeInterval:1 
                                             target:self 
                                           selector:@selector(betLoop:) 
                                           userInfo:nil 
                                            repeats:YES];

它被添加到当前运行循环并被当前运行循环保留 by that method ,因此您无需手动执行此操作。只需[myRunLoop run]。您的计时器的选择器参数也无效 - 计时器的“目标方法”needs to look like this :

- (void)timerFireMethod:(NSTimer *)tim;

这也意味着,如果您只想使计时器无效,则无需保留计时器,因为您可以从该方法内部引用它。

其次,不清楚“此线程需要 sleep 以等待输入”是什么意思。当您安排该计时器时,将在同一线程上调用方法 (betLoop)。如果您要使线程休眠,计时器也会停止。

您似乎对方法/线程有点困惑。 方法 bet 正在您的线程上运行。它本身不是一个线程,并且可以从该线程上的 bet 调用其他方法。如果您希望一个方法等待另一个方法完成,您只需在第一个方法中调用第二个方法即可:

- (void)doSomethingThenWaitForAnotherMethodBeforeDoingOtherStuff {
    // Do stuff...
    [self methodWhichINeedToWaitFor];
    // Continue...
}

我认为你只是想让投注回归;运行循环将使线程保持运行,正如我所说,您从线程上的方法调用的其他方法也在线程上。然后,当您完成倒计时时,调用另一个方法来完成任何需要完成的工作(您也可以使 betLoop: 内的计时器无效),并完成线程:

- (void)takeCareOfBusiness {
  // Do the things you were going to do in `betting`
  // Make sure the run loop stops; invalidating the timer doesn't guarantee this
  CFRunLoopStop(CFRunLoopGetCurrent());    
  return;    // Thread ends now because it's not doing anything.
}

最后,由于定时器的方法是在同一个线程上,所以不需要使用performSelector:onThread:...;正常调用该方法即可。

您应该看看 Threading Programming Guide .

另外,不要忘记释放您创建的 bettingThread 对象。

关于Objective-C:阻塞线程直到 NSTimer 完成(iOS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5772977/

相关文章:

java - 如何在Java中捕获同时执行多个查询的响应时间?

ios - Swift - 如何在协议(protocol)上使用 KVO 的 'observe' 方法

iOS UIBarButtons 不设置由 UIActionSheet iOS 6.1 启用

objective-c - nsmutabledictionary 没有可见的接口(interface)声明选择器 setobject :forkey:

ios - 使用 NSDictionaries 的 NSMutableArray 对 UITableView 进行分段

ios - 在应用程序运行时在 AppDelegate 中运行 didFinshLaunchingWithOptions?

ios - NSDateFormatter 问题 - 获取错误的日期

.net - 您在 UI 中使用 System.Component.BackgroundWorker 的频率如何? (如果曾经)

Java创建定期执行某些操作的后台线程

xcode - 用于更改Xcode DerivedData位置的命令行选项