2016-02-19 91 views
0

對於項目,我需要使用CoreLocation服務,但使用其他語言。但是,這個問題是一個無限的NSRunLoop。我試圖使用觀察員,但沒有任何成功。我沒有得到任何東西無法在控制檯應用程序中停止NSRunLoop

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations 

所以我在運行循環中等待位置更新。我可以使用runUntilDate,但我需要確保用戶在接下來的3/5/10秒內點擊Ok。

所以,這裏是我的代碼:

#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; 
} 

預先感謝您。 乾杯

回答

1

一般來說,你不應該使用無限制run。您必須提供停止循環的能力。在你的情況下,它可以是這樣的:

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

Apple doc about Run Loops

+0

哦,謝謝,你真的救了屁股:) –

相關問題