我对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];
}
TestViewController.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
来创建视图控制器。
提前谢谢!
答案 0 :(得分:0)
我认为您的问题是您在第一个视图控制器的[locationManager startUpdatingLocation]
方法中执行viewDidLoad
,然后在[locationManager stopUpdatingLocation]
方法中执行- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations
。
我的猜测是,您收到了该位置,并且在实例化TestViewController
之前停止了位置管理器,这意味着尚未注册观察者。