【问题标题】:iOS 10: CLManager as a separate class - receiving call backsiOS 10:CLManager 作为一个单独的类 - 接收回调
【发布时间】:2017-04-08 04:44:39
【问题描述】:

我是 iOS 开发的新手,我正在尝试构建一个在多个视图控制器中使用用户位置的应用程序。我试图在一个单独的类中实现位置管理器,然后在有新位置可用时将位置从回调函数发送到视图控制器。我见过一个使用单例但想使用协议方法的实现——我过去见过这样的例子,我再也找不到了,而且效果很好。

人们能否建议以这种方式设计它的最佳方式是什么?以下是我的一个视图控制器和位置管理器类的一些关键部分,供参考。

ViewController.m

- (void)viewDidLoad {

locMan = [[LocClass alloc] init]; 
[locMan startLocationManager]; 
...
}

LocClass.m(位置管理器类)

 - (void)startLocationManager {
 [self.coreLocationManager startUpdatingLocation];
 }

 - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
 //the usual stuff here...
}

如果可用,我如何使用协议方法将位置从 didUpdateLocations: 发送回 ViewController.m?如果可能的话,参考一个例子会很好。

【问题讨论】:

标签: ios iphone location protocols core-location


【解决方案1】:

在 LocClass.h 文件中添加协议方法

@protocol LocationUpdateProtocol <NSObject>
@optional
// Override this method in UIViewController derived class to get back the location details.
-(void)locationUpdatedWithManager:(CLLocationManager *)manager newLocations:(NSArray *)locations;
@end

@interface LocClass : NSObject
@property (nonatomic, weak) NSObject<LocationUpdateProtocol> *delegate;
@end

然后在你的 .m 文件中

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
 //the usual stuff here...

   if([self.delegate conformsToProtocol:@protocol(LocationUpdateProtocol)] && [self.delegate respondsToSelector:@selector(locationUpdatedWithManager:newLocations:)]) {
        [self.delegate locationUpdatedWithManager:manager newLocations:locations];
    }
}

现在 mainViewcontroller 类应该实现这个协议

@interface ViewController () <LocationUpdateProtocol>

还有你初始化位置管理类的地方,设置委托

- (void)viewDidLoad {

locMan = [[LocClass alloc] init]; 
[locMan startLocationManager]; 
locMan.delegate = self;
...
}

//Will get the delegate callback here.
 - (void)locationUpdatedWithManager:(CLLocationManager *)manager newLocations:(NSArray *)locations{
}

【讨论】:

    猜你喜欢
    • 2016-12-01
    • 1970-01-01
    • 2012-07-15
    • 1970-01-01
    • 2021-11-25
    • 2020-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多