【发布时间】:2015-02-01 16:41:11
【问题描述】:
我正在尝试使用静态类 MyClass 作为其自己的静态 CLLocationManager 成员的委托,但我实现的 CLLocationManager 委托方法没有被调用。我已将委托设置为[myClass class],正确实现了委托方法,并将协议包含在 MyClass.h 中。
MyClass.h
@interface iOSSonic : NSObject <CLLocationManagerDelegate>
MyClass.m
locationManager 声明:
@implementation myClasss : NSObject
...
static CLLocationManager *locationManager = nil;
我正在通过以下方法懒惰地实例化静态 CLLocationManager:
+(CLLocationManager*)getLocationManager {
if (locationManager == nil) {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = [myClass class]; // we set the delegate of locationManager to self.
locationManager.desiredAccuracy = kCLLocationAccuracyBest; // setting the accuracy
locationManager.distanceFilter = 0.5; // get updates for location changes > 0.5 m
[locationManager requestWhenInUseAuthorization];
}
return locationManager;
}
...然后从我的 ViewController 调用以下 MyClass 方法:
+(void)myFunction {
[self.getLocationManager startUpdatingLocation];
}
委托方法实现:
...
+(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
...
}
+(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
...
}
ViewController.m
// no initialization needed for static myClass
- (IBAction)onButtonClick:(id)sender {
[myClass myFunc] // This should trigger the didUpdateLocations delegate method, but it doesn't
为了确保这不是与让委托是静态(不可实例化)类和委托回调是类方法相关的问题,我还尝试将 locationManager 作为@property 而不是静态成员,并且创建了一个 myClass 的实例,将 myClass 的 locationManager 的委托设置为 self。我还将getLocationManager 替换为覆盖的locationManager getter,并将委托回调更改为实例方法。
MyClass.m
初始化:
-(id)init {
if (self = [super init]) {
// do nothing
}
return self;
}
LocationManager 声明和实例化:
...
@interface MyClass()
@property (strong, nonatomic) CLLocationManager *locationManager;
@end
@implementation
...
// Lazily instantiate locationManager
-(CLLocationManager*)locationManager {
if (!_locationManager) {
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self; // we set the delegate of locationManager to self.
_locationManager.desiredAccuracy = kCLLocationAccuracyBest; // setting the accuracy
_locationManager.distanceFilter = 0.5; // get updates for location changes > 0.5 m
[_locationManager requestWhenInUseAuthorization];
}
return _locationManager;
}
委托方法实现:
...
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
...
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
...
}
ViewContoller.h
...
@property (strong, nonatomic) myClass *myClassInstance;
...
ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
...
self.myClassInstance = [[myClass alloc] init];
我做错了什么?
【问题讨论】:
标签: ios objective-c delegates static-methods static-members