我想从应用程序的其他地方调用一个方法来获取在应用程序委托(delegate)中获取的用户位置。当从另一个 View Controller 调用 CLLocation *getCurLoc = [AppDelegate getCurrentLocation];
时,没有任何返回。
App Delegate 是,
@synthesize locationManager;
CLLocation *location;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
locationManager = [[CLLocationManager alloc]init];
locationManager.delegate = self;
locationManager.desiredAccuracy=kCLLocationAccuracyKilometer;
[locationManager startUpdatingLocation];
return YES;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
[locations lastObject];
[manager stopUpdatingLocation];
CLLocation *location = [locations lastObject];
}
+(CLLocation *)getCurrentLocation{
return location;
}
将其更改为带有“-”的实例方法无效。 “位置”应该成为一个实例吗?应该将委托(delegate)制作成一个实例,还是有更好的方法从其他地方访问它?
最佳答案
在 didUpdateLocations
中,您定义并设置了一个本地变量location
,而不是全局变量 location
定义在文件的顶部。换行
CLLocation *location = [locations lastObject];
到
location = [locations lastObject];
会解决问题。但更好的解决方案是使用 AppDelegate 类中的属性。 您可以在类扩展中定义它:
@interface AppDelegate ()
@property(strong, nonatomic) CLLocation *location;
@end
然后你在实例方法中访问它
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
[locations lastObject];
[manager stopUpdatingLocation];
self.location = [locations lastObject];
}
在类方法中
+(CLLocation *)getCurrentLocation{
// Get the instance:
AppDelegate *app = [[UIApplication sharedApplication] delegate];
return app.location;
}
更新:如果声明 AppDelegate 符合某些协议(protocol)(在 公共(public)接口(interface)或在类扩展中),例如:
@interface AppDelegate () <CLLocationManagerDelegate>
@property(strong, nonatomic) CLLocation *location;
@end
然后上面的代码创建了一个警告
initializing 'AppDelegate *__strong' with an expression of incompatible type 'id<UIApplicationDelegate>'
并且需要显式转换:
+(CLLocation *)getCurrentLocation{
// Get the instance:
AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
return app.location;
}
关于ios - ios 中的应用程序委托(delegate)未调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19746090/