我对线程很陌生,所以请亲切。
在用户通过身份验证后的Login View Controller中,我每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]
}
...
答案 0 :(得分:1)
我建议使用GCD。
dispatch_queue_t dq = dispatch_queue_create("bkgrndQueue", NULL);
dispatch_async(dq, ^{
@autoreleasepool{
while(SEMAPHORE_NAME){
// do stuff in here
}
}
}
然后在你的其他视图控制器中
SEMAPHORE_NAME = NO;