无法在控制台应用程序中停止 NSRunLoop

Cannot stop NSRunLoop in a console app

对于一个项目,我需要使用另一种语言的 CoreLocation 服务。然而,问题是一个无限的 NSRunLoop。我尝试使用观察者但没有成功。我在

中没有得到任何东西
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

所以我在 运行 循环中等待位置更新。我可以使用 运行UntilDate 但我需要确保用户将在接下来的 3/5/10 秒内单击“确定”。

所以,这是我的代码:

#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>

@interface Location : NSObject <CLLocationManagerDelegate>
@property (nonatomic, retain)CLLocationManager *manager;
@property (nonatomic, retain)NSTimer *timer;

@end

@implementation Location

- (instancetype)init {
    if (self = [super init]) {
        _manager = [[CLLocationManager alloc] init];
        _manager.delegate = self;
    }

    return self;
}

- (void)dealloc {
    [_manager release];
    [_timer release];
    [super dealloc];
}

- (void)launch
{
    [_manager startUpdatingLocation];

    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1
                                     target:self
                                   selector:@selector(checkIfUpdated:)
                                   userInfo:nil
                                    repeats:YES];
    [_timer release];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
}

- (void)checkIfUpdated:(NSTimer *)timer
{
    if (_manager.location != nil) {
        [timer invalidate];
        [timer release];
        NSLog(@"invalidate the timer %@", timer);
    }
}


- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"Error %@", error.userInfo);
    [_timer invalidate];
    [_timer release];
}

@end


int main(int argc, const char * argv[]) {
    Location *location = [[Location alloc] init];

    [location launch];

    NSString *str = [NSString stringWithFormat:@"%f, %f", location.manager.location.coordinate.latitude,
                     location.manager.location.coordinate.longitude];
    [str release];
    NSLog(@"%s", [str UTF8String]);
    return 0;
}

提前谢谢你。 干杯

一般来说,您永远不应该使用无限制 run。您必须提供停止循环的能力。在您的情况下,它可能是这样的:

while (!cancelled && !buttonTouched)
{
    NSDate *nextDate = [NSDate dateWithTimeIntervalSinceNow:1.0];
    [[NSRunLoop currentRunLoop] runUntilDate:nextDate];
}

Apple doc about Run Loops