我对线程很陌生,所以请客气。
在对用户进行身份验证之后,在Login View Controller中,我启动了一个线程来每30秒获取一次用户地理位置(仅在用户登录时才想进行此操作),然后移至显示以下内容的应用程序的主视图控制器中:应用程序主要信息。
当用户注销时,我想取消创建的线程,该线程每30秒收集一次地理位置信息。
我该怎么做呢?
我接近这个正确吗?如果没有,请提供代码示例和解释
非常感谢!!!!
Loggin视图控制器
...
- (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。
dispatch_queue_t dq = dispatch_queue_create("bkgrndQueue", NULL);
dispatch_async(dq, ^{
@autoreleasepool{
while(SEMAPHORE_NAME){
// do stuff in here
}
}
}
然后在另一个视图控制器中
SEMAPHORE_NAME = NO;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句