ios - ios 中的应用程序委托(delegate)未调用方法

标签 ios objective-c delegates cllocationmanager

我想从应用程序的其他地方调用一个方法来获取在应用程序委托(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/

相关文章:

ios - NSDateComponent 给我一天递增 1

ios - 如何在脱机同步中处理核心数据关系-Azure移动服务iOS

ios - Objective-C:委托(delegate)系统在 Xcode 中无法正常工作

Swift 4 Mapview 没有调用委托(delegate)方法 f

ios - Swift:如何使用 UISwitch 来控制 UITextField 通过委托(delegate)启用或禁用

ios - Alamofire 火变量类型没有下标成员

ios - 在表格 View 中使用 swift 的 iAds

ios - 为什么 Button SubView 不会在 swift 4 中回到后面?

iphone - 添加或删除 View 时,NSViewController 会收到通知吗?

ios - 这些注册表单是如何在 ios 中创建的?