【问题标题】:Handling CLLocationManager delegate from another class处理来自另一个类的 CLLocationManager 委托
【发布时间】:2015-05-28 07:58:15
【问题描述】:

我有 2 个类作为 NSObject 子类:

第一类更可能充当适配器。它将数据发送到 Class2 以处理异步任务。当委托被解雇时,我想将数据发回适配器类。

在适配器类中:

Class2 *cls = [[Class2 alloc] init];
[ftc fetchLocation];

在 Class2.m 中

-(void)fetchLocation{

    if(IS_OS_8_OR_LATER) {
        [self.locationManager requestAlwaysAuthorization];
    }

    self.locationManager = [[CLLocationManager alloc] init];

    if ([CLLocationManager locationServicesEnabled]){
        NSLog(@"Enable");
    }
    self.locationManager.delegate =self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager requestAlwaysAuthorization];
    [self.locationManager startUpdatingLocation];
}

当我从适配器调用 fetch-location 方法时,它确实调用并读取行,但之后,Class2 消失并返回适配器类而不等待委托(didUpdateLocations)

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

    NSString *latitude = [NSString stringWithFormat:@"%f",self.locationManager.location.coordinate.latitude];
    NSString *longtitude = [NSString stringWithFormat:@"%f",self.locationManager.location.coordinate.longitude];
    NSString *altitude = [NSString stringWithFormat:@"%f",self.locationManager.location.altitude];
    NSString *speed = [NSString stringWithFormat:@"%f",self.locationManager.location.speed];

    NSDictionary *locationDictionary = @{@"latitude":latitude,@"longtitude":longtitude,@"altitude":altitude,@"speed":speed};    
    if (locations.count >0 && [locations isKindOfClass:[NSArray class]]) {
        [self.delegate userLocationHasUpdated:self :locationDictionary];
        [self.locationManager stopUpdatingLocation];
        self.locationManager = nil;
        return;
    }
}

但是,如果我只是运行 Class2 并从编译中删除适配器(使用第一个初始化程序),它会按预期运行,我该如何处理来自另一个触发的类的委托方法?

最好的问候。

【问题讨论】:

    标签: objective-c xcode ios8 cllocationmanager


    【解决方案1】:

    你有几个选择,真的。一个可能是让你的第二类成为你的第一类的财产(我猜单例模式在这里很合适)。然后你可以在你的第二个类中声明一个协议并通过委托方法通知你的第一个类(非单例实现)或使用NSNotificationCenter 发布通知(单例实现)。

    第二种选择是将带有完成处理程序的块传递给第二个类。例如,您可以像这样在第二个类中声明您的方法(如果需要,调整块的返回类型和参数):

    - (void)updateLocationWithCompletionHandler:(void (^)(void))completion;
    

    实现它,以便在获得地理位置更新结果后调用completion 块。

    并从第一类调用它,例如:

    [self.secondClass updateLocationWithCompletionHandler:^
          {
              // Your completion code here.
          }];
    

    希望这会有所帮助(抱歉,没有检查 Xcode 中的代码,如果有错别字,请排除错误)。

    【讨论】:

    • @InnaKamoze 很高兴它有帮助。顺便说一句,您可以使用 KVO 代替通知。最适合你的。
    【解决方案2】:

    iOS CLLocationManager in a separate class 可能重复。如果你想有单独的类来处理位置管理器,你必须创建一个单例类来获取位置。您将在共享链接中找到指导

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多