【问题标题】:Receiving CLLocation updates on a background thread在后台线程上接收 CLLocation 更新
【发布时间】:2010-10-22 20:04:23
【问题描述】:

我正在尝试使用 iPhone SDK 为位置更新实现(非并发)NSOperation。 NSOperation 子类的“肉”是这样的:

- (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 文档:

您的委托对象的方法是从您启动相应位置服务的线程中调用的。该线程本身必须有一个活动的运行循环,就像在应用程序的主线程中找到的那样。

我不知道还有什么可以尝试的。也许它正盯着我的脸......感谢任何帮助。

提前致谢!

【问题讨论】:

    标签: iphone core-location cllocationmanager


    【解决方案1】:

    您缺少“活动运行循环”部分。在 start 方法的末尾添加:

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

    【讨论】:

    • 所以它盯着我的脸 :) 我认为我不必手动运行 runloop,因为 NSOperationQueue 管理线程(及其 runloop) .我想情况并非如此。谢谢!
    猜你喜欢
    • 2015-03-20
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    • 1970-01-01
    • 2016-03-30
    • 2012-04-24
    • 2013-11-23
    相关资源
    最近更新 更多