我正在尝试编写一个可以更新设备位置的应用程序。
我设置了GPS_Obtainer类,它将获取设备的位置。GPS_Obtainer类会将位置信息转发给视图控制器。
我尝试使用协议,但失败了。
最好的方法是什么?如何?
您可以选择使用所有这三个是它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];
}
希望以上有帮助。
干杯。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句