2014-11-02 76 views
0

我对线程非常陌生,所以请亲切。在另一个视图控制器中停止线程

在用户通过身份验证后的登录视图控制器中,我启动一个线程以每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] 
} 
... 
+1

尝试直接使用队列,而不是线程。看看GCD和[并发编程指南](https://developer.apple.com/library/ios/documentation/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html) – Abizern 2014-11-02 23:20:53

+0

NSOperationQueue或NSTimer会比即时睡眠组合。 – 2014-11-02 23:24:47

+0

您可以在注销时取消队列或计时器。 – 2014-11-02 23:30:33

回答

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; 
+0

哪里有一个地方SEMAPHORE_NAME,以确保它可用于所有视图控制器?它是什么类型? - 非常感谢 – lr100 2014-11-07 16:34:52

+1

bool/BOOL/Bool,你应该在你的AppDelegate中声明它为extern(创建一个“超全球”) – TheLivingForce 2014-11-07 17:22:49

+0

谢谢。这个解决方案正在为我工​​作! – lr100 2014-11-07 18:08:09

相关问题