开发者

I am working on the codes to get location of user and get stuck

First please take a look at codes below

CoreLocationController.h
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>

@protocol CoreLocationControllerDelegate     // Line 1
@required                       

- (void)locationUpdate:(CLLocation *)location;
- (void)locationError:(NSError *)error;

@end

/* Declare class named CoreLocationControll and inherited from CLLocationManagerDelegate */
@interface CoreLocationController : NSObject <CLLocationManagerDelegate> {
    CLLocationManager *locMgr;
    id delegate;
}

@property (nonatomic, retain) CLLocationManager *locMgr;            // claim setter and getter for locMgr
@property (nonatomic, assign) id delegate;                          // claim setter and getter for delegate

@end


CoreLcationController.m
#import "CoreLocationController.h"

@implementation CoreLocationController
@synthesize locMgr, delegate;

/* Is trig开发者_JAVA技巧gered by - (void)startUpdatingLocation from CoreLocationDemoViewController.m*/
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    NSLog(@"CORE_LOCATION_CONTROLLER=======>DID_UPDATE_TO_LOCATION");
    if([self.delegate conformsToProtocol:@protocol(CoreLocationControllerDelegate)]) // line 2
        [self.delegate locationUpdate:newLocation];

}

My questions are what line 1 and line 2 do and why I looked up CoreLocationControllerDelegate but no reference on it


The lines you are asking about are objective-c protocol declarations. The code is declaring a protocol called CoreLocationControllerDelegate. A protocol is, in simple terms, a list of methods that, a given object can be expected to implement if it conforms to the protocol.

For example, the UITextFieldDelegate protocol contains the various methods that an object should or must implement if it wants to be the delegate for a text field.

Line 1 @required means that the object has to implement the following methods to conform to the protocol. If you declare your object as conforming to the protocol, it must implement those methods or you will get build errors (or warnings, I can't remember which).

Line 2 is a safety check to make sure that the delegate conforms to the protocol (in this case, that it implements the required methods) before the delegate methods are called. This prevents a runtime crash where an unrecognised selector is sent to the object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜