【问题标题】:objective-c getting location and notifiy if updated. observer? how?objective-c 获取位置并在更新时通知。观察者?如何?
【发布时间】:2013-06-30 09:45:45
【问题描述】:

我使用 locationmanger 来获取我在 iPhone 上的当前位置。

#pragma mark - Location handling
-(void)doLocation {
    self.locationManager = [[CLLocationManager alloc] init];
    [...]
    SingletonClass *sharedSingleton = [SingletonClass sharedInstance];
    sharedSingleton.coordinate = [location coordinate];
}

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    [...]
    SingletonClass *sharedSingleton = [SingletonClass sharedInstance];
    [sharedSingleton setCoordinate:CLLocationCoordinate2DMake(currentLat, currentLng)];

    NSLog(@"debug: self.currentLoc: %@", self.currentLoc);

}

这很好用,我得到了一些延迟的位置坐标,并且可以通过 sharedSingleton 访问它们。当我有坐标时,我必须触发另一个需要坐标作为参数的函数。

我的问题从这里开始......

现在,当检索到坐标并且我可以调用需要坐标作为输入参数的其他函数时,我该怎么做。有没有我可以使用的观察者?如果,我该如何实施?

我只需要一些告诉我的东西:嘿,伙计,坐标可以使用,这样我就可以触发下一个功能..

【问题讨论】:

    标签: objective-c triggers location cllocationmanager observer-pattern


    【解决方案1】:

    您可以使用NSNotificationCenter 或委托。目标 C 中的委托模式非常普遍。为此,您需要在 .h 文件中实现一个协议,如下所示:

    @protocol MyLocationManagerDelegate <NSObject>
    - (void) locationManager:(MyLocationManager *)manager didFindLocation:(CCLocation*) location
    @end
    
    //still in your .h file add a delegate that implements this protocol
    @property (nonatomic, assign) id<MyLocationManagerDelegate> delegate
    

    然后在找到坐标时必须采取行动的其他类中,表明它实现了MyLocationManagerDelegate协议,并实现了- (void) locationManager:(MyLocationManager *)manager didFindLocation:(CCLocation*) location方法。

    分配您的位置经理后,将您的其他班级设置为代表。在您的didUpdateToLocation 方法中只需调用[self.delegate locationManager:self didFindLocation:self.currentLoc]

    【讨论】:

    • 查看了委托模式enroyed.com/ios/…。在我看来要走的路。现在必须使用您建议的解决方案测试 ist
    【解决方案2】:

    实现此功能的一种方法是 NSNotificationCenter。

    这篇文章将向您展示如何通过 NSNotificationCenter 设置通知。

    Send And Recieve Messages Through NSNotificationCenter In Objective-c

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-26
      • 2011-12-05
      相关资源
      最近更新 更多