我正在尝试使用静态类MyClass
作为其自己的静态CLLocationManager
成员的委托,但我实现的CLLocationManager
委托方法不是调用。我已将委托设置为[myClass class]
,正确实现了委托方法,并将协议包含在MyClass.h中。
@interface iOSSonic : NSObject <CLLocationManagerDelegate>
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 {
...
}
// 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。我还用重写的locationManager getter替换了getLocationManager
,并将委托回调更改为实例方法。
初始化:
-(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 {
...
}
...
@property (strong, nonatomic) myClass *myClassInstance;
...
- (void)viewDidLoad
{
[super viewDidLoad];
...
self.myClassInstance = [[myClass alloc] init];
我做错了什么?
答案 0 :(得分:0)
这是一个愚蠢的位置服务权限的事情。事实证明它与静态成员,类与实例等无关。这为我解决了这个问题:https://stackoverflow.com/a/25765345/1402368
当然这是愚蠢的......
答案 1 :(得分:-1)
以下是我对正在发生的事情的理解:
实例方法调用和类方法调用在Objective-C中在语义上是不同的,并且不可互换。
方法声明:
+(void)someMethod;
和
-(void)someMethod;
定义2种不同的方法。要调用它们,您必须知道您是在调用实例方法还是类方法,并相应地进行编码。
编写位置管理器以在其委托上调用 INSTANCE 方法,而不是类方法。
因此,你不能做你想要做的事情(使CLASS成为委托而不是类的实例。)
您可能能够设计自己的自定义类,其对象希望将类设置为其委托,但之后您只能将类指定为委托,而不是该类的实例。