私はiOS開発(私の最初のアプリ)にかなり慣れていないので、この問題に直面しました。
ユーザーがボタンをタッチすると、複数のViewControllerでユーザーの現在の場所を取得する必要があるiPhoneアプリがあります。冗長なコードを防ぐために (異なるビュー コントローラーで 、 などを複数回実装locationManager:didFailWithError
するlocationManager:didUpdateToLocation:fromLocation
)、次のようなカスタム クラスを作成することにしましたLocationManager
。
LocationManager.h
@interface LocationManager : NSObject <CLLocationManagerDelegate> {
@private
CLLocationManager *CLLocationManagerInstance;
id<LocationManagerAssigneeProtocol> assignee;
}
-(void) getUserLocationWithDelegate:(id) delegate;
LocationManager.m
@implementation LocationManager
-(id)init {
self = [super init];
if(self) {
CLLocationManagerInstance = [[CLLocationManager alloc] init];
CLLocationManagerInstance.desiredAccuracy = kCLLocationAccuracyBest;
CLLocationManagerInstance.delegate = self;
}
return self;
}
-(void) getUserLocationWithDelegate:(id) delegate {
if([CLLocationManager locationServicesEnabled]) {
assignee = delegate;
[CLLocationManagerInstance startUpdatingLocation];
}
}
#pragma CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
...
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
[CLLocationManagerInstance stopUpdatingLocation];
[assignee didUpdateToLocation:newLocation];
}
ViewControllersが実装するLocationManagerAssigneeProtocolというプロトコルがあります
@protocol LocationManagerAssigneeProtocol <NSObject>
@required
-(void) didUpdateToLocation:(CLLocation *) location;
@end
そして、必要に応じてビューコントローラーで
- (IBAction)getMyLocation:(id)sender {
[locationMgr getUserLocationWithDelegate:self];
}
LocationManager
このコードは完全に機能しますが、Location Manager の呼び出しを開始したクラスの関数を呼び出せるようにすることで、ここでいくつかの設計パターンに違反していると感じています。一方、場所で動作するはずのすべてのビューコントローラーにCLLocationManagerDelegateを実装したくありません。
この問題に対するより良い解決策はありますか?