I'm getting a bit confused how delegation works. I believe the idea is to have another class do the work for you and call you back. So if you did something like this:
- (void)viewDidLoad {
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if (CLLocationManager.locationServicesEnabled == YES) {
NSLog(@"location enabled");
latitudeLabel.text = [NSString stringWithFormat:@""];
[locationManager startUpdatingLocation];
}
NSLog(@"%g", locationCoordinate.latitude);
}
If I NSLog the coordinate in the viewDidLoad, even though I startUpdatingLocation, the value of my locationCoordinate property is 0. But if I NSLog the value in the delegate method like so:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSString *latitudeString = [[NSString alloc] initWithFormat: @"%g m", newLocation.coordinate.latitude];
latitudeLabel.text = latitudeString;
[latitudeString release];
locationCoordinate = newLocation.coordinate;
NSLog(@"in delegate: %g", locationCoordinate.latitude);
}
I get an actual location value. I thought that by using the delegate method, my locationProperty would get set, but it seems not to. Am I understanding delegation incorrectly? Thanks.
A major reason why delegates exist is in fact in situations like the one you describe.
You have some functionality in a class, but the functionality is asynchronous, i.e. you can't just go get the info right off the bat, or it's implemented asynchronously (for example, downloading a huge file off the net should/does happen asynchronously, to not lock up the whole interface for a minute+).
So using delegation you can say "just become my delegate and I'll eventually get back to you, we're done for now". The object can then return back to the caller at its convenience, rather than the opposite (being called only when the main application wants it).
As said, downloading files and such is exactly where delegation comes into play. It's also a very useful tool for your own coding to incorporate delegates in your code, in cases where you either have to wait on delegation from some other object (such as CLLocationManager), or you have to process something on a separate thread (such as parsing data or whatnot).