我有一个循环函数,其中称为 [NSThread sleepForTimeInterval:2.0];。这意味着 2 秒后,循环函数被调用。我想在传递新视图时,这个循环函数停止,当返回时,再次调用它。
我使用这段代码来调用循环函数:
-(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 仍然调用。它不会停止。你有什么建议吗?