2010-10-22 51 views
4

我正在嘗試使用iPhone SDK實現位置更新(非併發)NSOperation。在該子類的NSOperation的「肉」是這樣的:在後臺線程上接收CLLocation更新

- (void)start { 
    // background thread set up by the NSOperationQueue 
    assert(![NSThread isMainThread]); 

    if ([self isCancelled]) { 
     return; 
    } 

    self->locationManager = [[CLLocationManager alloc] init]; 
    locationManager.delegate = self; 
    locationManager.desiredAccuracy = self->desiredAccuracy; 
    locationManager.distanceFilter = self->filter; 
    [locationManager startUpdatingLocation]; 

    [self willChangeValueForKey:@"isExecuting"]; 
    self->acquiringLocation = YES; 
    [self didChangeValueForKey:@"isExecuting"]; 
} 

- (void)cancel { 
    if (! self->cancelled) { 
     [self willChangeValueForKey:@"isCancelled"]; 
     self->cancelled = YES; 
     [self didChangeValueForKey:@"isCancelled"]; 

     [self stopUpdatingLocation]; 
    } 
} 

- (BOOL)isExecuting { 
    return self->acquiringLocation == YES; 
} 

- (BOOL)isConcurrent { 
    return NO; 
} 

- (BOOL)isFinished { 
    return self->acquiringLocation == NO; 
} 

- (BOOL)isCancelled { 
    return self->cancelled; 
} 



- (void)stopUpdatingLocation { 
    if (self->acquiringLocation) { 
     [locationManager stopUpdatingLocation]; 

     [self willChangeValueForKey:@"isExecuting"]; 
     [self willChangeValueForKey:@"isFinished"]; 
     self->acquiringLocation = NO; 
     [self didChangeValueForKey:@"isExecuting"]; 
     [self didChangeValueForKey:@"isFinished"]; 
    } 
    locationManager.delegate = nil; 
} 


- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { 
    assert(![NSThread isMainThread]); 

    // ... I omitted the rest of the code from this post 

    [self stopUpdatingLocation]; 
} 

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)theError { 
    assert(![NSThread isMainThread]); 
    // ... I omitted the rest of the code from this post 
} 

現在,在主線程我創建這個操作的實例,並將其添加到NSOperationQueue。 start方法被調用,但是沒有一個-locationManager:...委託方法被調用。我不明白爲什麼他們永遠不會打電話。

我確實使接口遵守<CLLocationManagerDelegate>協議。我讓NSOperationQueue管理線程進行此項操作,所以都應該符合CLLocationManagerDelegate文檔:

您的委託對象的方法是從你開始的相應位置服務的線程調用。該線程本身必須有一個活動的運行循環,就像在應用程序的主線程中找到的一樣。

我不知道還有什麼可以嘗試這個工作。也許它正在盯着我......任何幫助表示讚賞。

在此先感謝!

回答

6

您錯過了「主動運行循環」部分。在你的啓動方法結尾添加:

while (![self isCancelled]) 
    [[NSRunLoop currentRunLoop] runUntilDate:someDate];

+0

因此,它*在我臉上凝視着:)我不認爲我必須手動運行runloop,因爲NSOperationQueue管理線程(和它的runloop) 。我想不是這種情況。謝謝! – octy 2010-10-25 13:22:08