Set delegate of CLLocationManager (Two different ways, are they equal?)

拜拜、爱过 提交于 2019-12-11 19:56:42

问题


Working on a tutorial with CLLocationManager where I set the delegate within the init method:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) 
    {
        locationManager = [[CLLocationManager alloc] init];
        [locationManager setDelegate:self];
        [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        [locationManager startUpdatingLocation];
    }
    return self;
}

Set the delegate:

[locationManager setDelegate:self];

In another tutorial I set the delegate in a header file:

@interface MyViewController : UIViewController <CLLocationManagerDelegate>

Are they equal? Whats the difference (if there is one)?


回答1:


You will need both of them if you want to implement and get callbacks from the delegate of CLLocationManger

You specify this in the header

@interface MyViewController : UIViewController <CLLocationManagerDelegate>

This tells xcode that MyViewController will implement the CLLocationManagerDelegate methods. If there are non-optional delegate methods, xcode will remind you to implement them.

With the line below

[locationManager setDelegate:self];

You tell your instance of CLLocationManager (locationManager) that MyViewController (self) will be the delegate and it should call all the implemented CLLocationManagerDelegate methods that you have implemented (if needed)




回答2:


Those are 2 different things.

CLLocationManagerDelegate is a protocol.
[locationManager setDelegate:self] just sets the objects delegate, so CLLocationManager can call the implemented delegate methods. For this to work correctly, self must conform to the CLLocationManagerDelegate protocol.

In other words, you need to do both.



来源:https://stackoverflow.com/questions/10246312/set-delegate-of-cllocationmanager-two-different-ways-are-they-equal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!