我对线程非常陌生,所以请亲切。在另一个视图控制器中停止线程
在用户通过身份验证后的登录视图控制器中,我启动一个线程以每30秒获取用户地理位置(只在用户登录时要执行此操作),然后移动到主视图控制器显示应用程序主要信息的应用程序。
当用户注销时,我想取消创建的线程以每30秒收集一次地理位置。
我该怎么做?
我接近这个正确吗?如果没有,代码示例和解释请
非常感谢!
洛 - 视图 - 控制器
...
- (IBAction)loginButton:(id)sender {
NSInteger success = 0;
//Check to see if the username or password texfields are empty or email field is in wrong format
if([self validFields]){
//Try to login user
success = [self loginUser];
}
//If successful, go to the MainView
if (success) {
//Start getting users Geolocation in a thread
[NSThread detachNewThreadSelector:@selector(startGeolocation:) toTarget:self withObject:nil];
//Go to Main view controller
[self performSegueWithIdentifier:@"loginSuccessSegue" sender:self];
}
else
{
//Reset password text field
self.passwordTextField.text = @"";
}
}
...
//Thread to get Geolocation every 30 seconds
-(void)startGeolocation:(id)param{
self.geoLocation = [[GeoLocation alloc] init];
while(1)
{
//****************START GEOLOCATION*******************************//
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate.databaseLock lock];
NSLog(@"Geolocation:(%f,%f)", [self.geoLocation getLatitude], [self.geoLocation getLongitude]);
sleep(30);
[appDelegate.databaseLock unlock];
}
}
主视图控制器
...
//When the Logout Button in MenuView is pressed this method will be called
- (void)logoutButton{
//Cancel the geolocation tread
//????????????????????????????
//Log the user out
[self logoutUser]
}
...
尝试直接使用队列,而不是线程。看看GCD和[并发编程指南](https://developer.apple.com/library/ios/documentation/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html) – Abizern 2014-11-02 23:20:53
NSOperationQueue或NSTimer会比即时睡眠组合。 – 2014-11-02 23:24:47
您可以在注销时取消队列或计时器。 – 2014-11-02 23:30:33