我正在尝试编写一个可以更新设备位置的应用。
我设置了一个GPS_Obtainer类,它将获取设备的位置。和GPS_Obtainer类将位置信息转发给视图控制器。
我尝试使用协议,但失败了。
最好的方法是什么?如何?
答案 0 :(得分:1)
您可以选择使用全部三个Notification
,Observers
或Protocol
来发送位置更新,我正在演示协议方式,请参阅下文
首先,您可以为Singleton
课程创建GPS_Obtainer
,如下所示。
<强> GPS_Obtainer.h
强>
#import "GPS_Obtainer.h"
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
@protocol GPS_ObtainerDelegate <NSObject>
-(void)locationDidUpdated:(CLLocation *)location;
@end
@interface GPS_Obtainer : NSObject
@property (nonatomic, strong) id<GPS_ObtainerDelegate> delegate;
+ (GPS_Obainer*)sharedSingleton;
@end
<强> GPS_Obtainer.m
强>
@interface GPS_Obtainer()<CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager* locationManager;
@end
@implementation GPS_Obtainer
- (id)init {
self = [super init];
if(self) {
self.locationManager = [CLLocationManager new];
[self.locationManager setDelegate:self];
[self.locationManager startUpdatingLocation];
}
return self;
}
+ (GPS_Obtainer*)sharedSingleton {
static GPS_Obtainer *sharedSingleton = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedSingleton = [GPS_Obtainer new];
});
return sharedSingleton;
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if(self.delegate && [self.delegate respondsToSelector:@selector(locationDidUpdated:)]){
[self.delegate locationDidUpdated:newLocation];
}
}
@end
然后你只需要在ViewController中设置类的委托,它将接收它,如下所示
<强> ViewController.m
强>
-(void)viewDidLoad{
[[GPS_Obtainer sharedSingleton] setDelegate:self];
}
-(void)locationDidUpdated:(CLLocation *)location{
//HERE you get the location updates
}
-(void)dealloc{
[[GPS_Obtainer sharedSingleton] setDelegate:nil];
}
希望以上有所帮助。
干杯。