我对线程非常陌生,所以请多多指教。
在用户通过身份验证后的登录 View Controller 中,我启动一个线程以每 30 秒获取用户地理位置(只想在用户登录时执行此操作),然后移动到应用程序的主视图 Controller 显示应用程序的主要信息。
当用户注销时,我想取消为每 30 秒收集一次地理位置而创建的线程。
我该怎么做?
我接近这个正确吗?如果没有,请提供代码示例和解释
非常感谢!!!
登录 View Controller
...
- (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];
}
}
主视图 Controller
...
//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。
dispatch_queue_t dq = dispatch_queue_create("bkgrndQueue", NULL);
dispatch_async(dq, ^{
@autoreleasepool{
while(SEMAPHORE_NAME){
// do stuff in here
}
}
}
然后在你的另一个 View Controller 中
SEMAPHORE_NAME = NO;
关于ios - 在另一个 View Controller 中停止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26705609/