2010-01-13 87 views
0

我有一個觀察者是這樣的:iPhone - 觀察者/每x秒

[mapView.userLocation addObserver:self forKeyPath:@"location" options:0 context:NULL]; 

所以如果一個用戶改變他的地理定位的方法被調用。 但我希望該方法也應該每x秒調用一次,因爲如果用戶不移動,位置不會改變,所以方法不會被調用。但我必須做一些計算。

我該怎麼做?

非常感謝&最好的問候。

回答

3

使用一個定時器

NSTimer *timer; 
timer = [NSTimer timerWithTimeInterval:30 //seconds 
           target:self 
           selector:@selector(myMethodtoRun:) 
           userInfo:nil // send an object if you want 
           repeats:YES]; 

[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode]; 

以後,如果要取消計時器,在方法myMethodToRun,您可以無效

- (void) myMethodToRun:(NSTimer *)timer { 
    … 
    if (shouldStopTimer) { 
     [timer invalidate]; 
    } 
} 
+0

非常感謝,有效。但我有一個小問題。切換TabBar中的視圖或使用TabBar中的後退按鈕,定時器運行...在這兩種情況下,我怎麼能阻止它? – Tim 2010-01-13 17:11:06

+0

使viewDidDisappear上的計時器無效,並在viewDidAppear上重新啓動它(coneybeare獲得積分;我只是因爲我有一個類似的問題而打鳴) – justin 2010-01-13 17:36:28

+0

非常感謝,這很有效。 – Tim 2010-01-13 18:15:36

0

的MKMapView不給你過GPS設備多的控制。我建議使用CLLocationManager,以便您可以隨時執行更新。然後你可以使用NSTimer @coneybeare剛纔建議的。

在CLLocationManager中,你可以設置distanceFilter,我相信它和MKMapView中的觀察者完全一樣。