0

我对 NSNotification 感到沮丧。不知何故,我的视图控制器无法接收回调。我在互联网上浏览过,但没有找到任何解决方案。这是我的代码

SideBarViewController.h

- (void)postNotificationWithString:(NSString *)deviceLocation {

    NSString *notificationName = @"LocationDetectedNotification";

    NSDictionary *dict = [NSDictionary dictionaryWithObject:deviceLocation forKey:@"MyLocation"];

    [[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:nil userInfo:dict];

}

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

CLLocation *currentLocation = [locations lastObject];

if (currentLocation != nil) {
  lon = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
  lat = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
  [self postNotificationWithString:[NSString stringWithFormat:@"%@,%@", lat, lon]];

}
// Save battery consumption
[locationManager stopUpdatingLocation];
}

测试视图控制器.h

@implementation TestViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
    // Custom initialization


}
return self;
}

- (void)viewDidLoad {

     [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(useNotificationWithString:) name:@"LocationDetectedNotification" object:nil];

{
- (void)useNotificationWithString:(NSNotification*)notification {
    NSLog(@"Location Retrieved");
    NSDictionary *dict = [notification userInfo];
    self.location = [dict valueForKey:@"MyLocation"];

}

当我点击 时TestViewController,什么也没发生。我用于storyboard创建视图控制器。提前致谢!

4

1 回答 1

0

我认为你的问题是你[locationManager startUpdatingLocation]viewDidLoad你的第一个视图控制器的方法中做,然后你[locationManager stopUpdatingLocation]- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations方法中做。

我的猜测是您在实例化您的之前TestViewController收到了位置并停止了位置管理器,这意味着尚未注册观察者。

于 2013-09-03T15:00:59.757 回答