在NSOperation中使用代表 [英] Use of delegates in NSOperation

查看:131
本文介绍了在NSOperation中使用代表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 NSOperation 中使用 CLLocationManager 。作为其中的一部分,我需要能够 startUpdatingLocation 然后等到收到CLLocation后才能完成操作。

I am trying to make use of CLLocationManager in an NSOperation. As part of this I require the ability to startUpdatingLocation then wait until a CLLocation is received before completing the operation.

目前我已经完成了以下操作,但是似乎从未调用过委托方法。请问有人可以告知问题是什么吗?

At present I have done the following, however the delegate method never seems to be called. Please can someone advise what the issue is?

- (void)main
{
    @autoreleasepool {
        if (self.isCancelled)
            return;

        // Record the fact we have not found the location yet
        shouldKeepLooking = YES;

        // Setup the location manager
        NSLog(@"Setting up location manager.");
        CLLocationManager *locationManager = [[CLLocationManager alloc] init];
        locationManager.delegate = self;
        locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        [locationManager startUpdatingLocation];

        while (shouldKeepLooking) {

            if (self.isCancelled)
                return;

            // Do some other logic...
        }
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    // None of this ever seems to be called (despite updating the location)
    latestLocation = [locations lastObject];
    [manager stopUpdatingLocation];
    shouldKeepLooking = NO;
}


推荐答案

它将调用代表运行在与main相同的操作队列中的方法。默认情况下NSOperation队列是串行的。你的while循环只是永远旋转(因为操作永远不会被取消)并且你的委托方法的调用是坐在它后面的队列中永远无法运行。

Its going to call the delegate method in the same operation queue as main is running in. And NSOperation queues are serial by default. Your while loop is just spinning forever (because the operation is never cancelled) and the call to your delegate method is sitting in the queue behind it never able to run.

完全摆脱while循环,让操作完成。然后,当调用委托方法时,如果它被取消,则通过返回丢弃结果。

Get rid of the while loop entirely and let the operation finish. Then when the delegate method is called, if it's cancelled discard the result by returning.

这篇关于在NSOperation中使用代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆