iphone – 使用[NSThread sleepForTimeInterval:2.0]时可以停止或取消循环功能;在IOS

我有一个循环函数,在其中称为[NSThread sleepForTimeInterval:2.0] ;.它意味着在2s之后,调用循环函数.我希望在传递新视图时,此循环函数停止,当返回时,再次调用它.

我用这段代码来调用循环函数:

-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    loop = YES;
    delete=NO;
    temp = [FileCompletedArray mutableCopy];
    NSOperationQueue *queue = [NSOperationQueue new];

    operations = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(updateArray) object:nil];
    [queue addOperation:operations];
    [operations release];

}

和循环功能:

-(void)updateArray{

   while (loop)
   {
        NSLog(@"start loop");

       if(loop){
        [NSThread sleepForTimeInterval:2.0];
        NSLog(@"start send request");


        NSURL *url1 = [NSURL URLWithString:@"http://server.com"];


        NSMutableURLRequest *afRequest = [httpClient requestWithMethod:@"POST" path:nil parameters:params1] ;

        operation= [[AFHTTPRequestOperation alloc] initWithRequest:afRequest];
      NSLog(@" request sent");
        [operation  setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

            NSLog(@"Server response1");

        }
      failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          NSLog(@"error: %@", error);
     }
         ];
        [httpClient enqueueHTTPRequestOperation:operation];
   }
       else
           return;
   }

}

并且viewdisappear()

-(void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    loop = NO;
    delete=NO;
    [operations cancel] ;
}

我的问题是当传递新视图时,updateArray仍然调用.它不会停止.你有什么建议吗?

最佳答案 您可以使用键值观察器进行尝试.您可以使用以下方法实现更改,这些更改将自动调用为特定值更改.首先,您必须设置要更改的ivar的通知.

[self addObserver:self forKeyPath:@"loop" options:NSKeyValueObservingOptionNew context:nil];

然后,您必须按照以下方法中的要求实现更改:

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
点赞