2016-11-17 79 views
0

下面是我的一些代碼片段CLLocationManager stopUpdatingLocation不會停止

BOOL checkingForLocation; 
. 
. 
. 
- (IBAction)LocationButtonTapped:(id)sender { 
    [locationManager startUpdatingLocation]; 
    checkingForLocation = YES; 
} 
. 
. 
. 
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations { 

    [locationManager stopUpdatingLocation]; 
    // locationManager = nil; 


    if (checkingForLocation) { 
     checkingForLocation = NO; 
     NSLog(@"here"); 
     // fetch data from server using location and present view controllers 
    } 
} 

didUpdateLocations被多次調用,因爲是的LocationManager持續更新每startUpdatingLocation位置。我的應用程序有一個錯誤,if(checkingForLocation)中的代碼多次運行並多次呈現視圖導致不期望的結果。

1)爲什麼stopUpdatingLocation不會停止對didUpdateLocations的進一步調用?

2)此外,如果checkingForLocation已經被設置爲NO爲什麼到didUpdateLocations隨後調用還是把checkingForLocationYES。那裏有種族條件嗎?

通過搜索其他SO問題,我發現設置locationManager = nil將停止對didUpdateLocations的額外調用,它確實解決了我的情況中的問題,但沒有真正的解釋。看來,stopUpdatingLocation應該照顧到這一點。任何見解都非常感謝。

謝謝

+0

你在哪裏調用'[locationManager startUpdatingLocation]; checkingForLocation = YES;'? – OgreSwamp

+0

@OgreSwamp我在按下按鈕時調用它。爲了清楚起見,我添加了上面的IBAction方法。 – galenom

回答

0

didUpdateLocations:可以頻繁地調用而由於其異步性質和optimisations的任何時間:

因爲它可能需要幾秒鐘返回初始位置時, 位置經理通常會立即傳送先前緩存的位置 數據,然後在 變爲可用時傳送更新的位置數據。因此,在採取任何操作之前,檢查任何位置對象的 時間戳總是一個好主意。如果兩個 位置服務都同時啓用,則它們使用相同的一組委託方法傳送事件 。

其實,如果你取消註釋locationManager = nil;它應該幫助,但如果你想用你的checkingForLocation屬性,你應該同步的分配。 @synchronized(self)是這種情況下最簡單的方法。