如何停止IOS中的调用循环功能



我想在视图不显示时停止调用循环函数。我该怎么做?这是我的代码:

    -(void) viewWillAppear:(BOOL)animated
{
    [self performSelectorInBackground:@selector(updateArray)  withObject:nil];
}

和:

    -(void)updateArray
{
while (1)
{
    NSLog(@"IN LOOP");
   [NSThread sleepForTimeInterval:2.0];
....}

updateArray通常在该视图消失时被调用。我想停止调用updateArray函数

提前感谢

生成BOOL iVar或属性

BOOL loopShouldRun;

在视图中WillAppear将其设置为YES

然后使用这个代码

-(void)updateArray
{
  while (loopShouldRun)
    {
      NSLog(@"IN LOOP");
      [NSThread sleepForTimeInterval:2.0];
....}
}

在视图中WillDisappear将其设置为NO.

但正如@Michael Deuterman在评论中提到的那样,当视图在sleepTimer启动之前消失时,可能会出现问题。

这是另一个NSTimer的解决方案。

  • 创建NSTimer iVar/@属性:@property (strong) NSTimer *timer;
  • viewWillAppear中创建计时器:

    timer = [NSTimer timerWithTimeInterval:2.0 invocation:@selector(updateArray) repeats:Yes]

  • viewWillDiappear中使计时器无效:

    if ([self.timer isValid]) { [self.timer invalidate] }

你的updateArray现在应该是这样的:

-(void)updateArray {
  NSLog(@"in loop");
}
while (1)
{
    NSLog(@"IN LOOP");
   [NSThread sleepForTimeInterval:2.0];
}

而(1)将永远为真。要停止它,你需要有一个条件来阻止循环的发生。

例如,

while (1)
{
    NSLog(@"IN LOOP");
   [NSThread sleepForTimeInterval:2.0];
   if(something happens)
    break;
}

希望它能帮助你。

这是一个简单的逻辑。。。只需获取一个标志变量,并在您的视图出现故障时更新该标志变量的值,然后

 - (void)viewWillDisappear:(BOOL)animated 

上述方法将在视图消失之前调用

viewDidDisappear:(BOOL)animated

上述方法也是可行的。将在您的视图消失后立即调用

所以你可以用上面的一种方法来改变你的标志变量的值。然后根据你的标志变数值,只要把break放在while循环中,你的循环就会中断.

使用NSThread而不是performSelector

NSThread *myThread; // preferable to declare in class category in .m file or in .h file

视图中将出现

myThread = [[NSThread alloc] initWithTarget:self selector:@selector(updateArray) object:nil];
[myThread start];

视图中WillDisappear

[myThread cancel]; // This will stop the thread and method will get stopped from execution
myThread = nil; // Release and nil object as we are re-initializing in viewWillAppear

有关更多详细信息,请参阅:NSThread类引用

最新更新