I’m trying to add city & state information to an MKAnnotation but the data is being cleared before I can add it to the annotation. Here is my current code (only showing the sections/parts of concern for simplicity):
in implementation:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
[self setCity:[placemark locality] andState:[placemark administrativeArea]];
}];
NSLog(@"Location 1: %@, %@", city, state);
MapPoint *mp = [[MapPoint alloc] initWithCoordinate:[newLocation coordinate]
title:[locationTitleField text]
date:[dateFormat stringFromDate:today]];
[mapView addAnnotation:mp];
}
- (void)setCity:(NSString *)c andState:(NSString *)s
{
[self setCity:c];
[city retain];
[self setState:s];
[state retain];
NSLog(@"Location 2: %@, %@", city, state);
}
in interface:
@interface AppDelegate : UIResponder <UIApplicationDelegate, CLLocationManagerDelegate, MKMapViewDelegate>
{
CLLocationManager *locationManager;
IBOutlet MKMapView *mapView;
NSString *city;
NSString *state;
}
@property (strong, nonatomic) IBOutlet UIWindow *window;
@property (nonatomic, copy) NSString *city;
@property (nonatomic, copy) NSString *state;
- (void)setCity:(NSString *)c andState:(NSString *)s;
@end
Location 1 prints (null), (null) while Location 2 prints San Francisco, California. Why is the data being erased from these properties before I can use them in my annotation?
Much thanks…
The reason Location 1 is null is that the reverse geocoder has not completed when it is run. Everything in your
completionHandlerwill occur after the geocoder finishes. Your log statement for location 1 is not part of thatcompletionHandlerand is executed immediately after the call to reverse geocode. The end result is that the log call occurs before you callsetCity:andState:.Update
You need to set the annotation in the
completionHandlerblock. The code which occurs in the block occurs later in sequence and time than the the rest of yourlocationManager:didUpdateToLocation:fromLocation:message implementation. You may wish to read about blocks from Apple’s documentation or search the internet.End Update
Also, it looks as if you may not be using properties as well as you could. Since you have a
cityandstateproperty, you do not need thecityandstateinstance variables.Try to change it as such:
In implementation:
You will not need the extra retain statements because the property copies the value. You must also be sure to call
self.cityandself.stateto get the values.