Storing an subtitle on an annotation with NSUserDefualts
- by Krismutt
Hey everybody!
Basically: what i try to do is to save the street address of an annotation so that when I quit the application and launch it again the street address still will be there...see the following code:
SavePosition.m
-(NSString *)subtitle{
if (!subtitle) {
return @"Ingen gata i närheten";
} else {
return subtitle;
}
}
-(NSString *)title{
return @"Sparad Position";
}
-(id)initWithCoordinate:(CLLocationCoordinate2D) coor{
self.coordinate=coor;
NSLog(@"%f,%f",coor.latitude,coor.longitude);
return self;
}
- (void)setCoordinate:(CLLocationCoordinate2D)koor {
MKReverseGeocoder *geocoder = [[[MKReverseGeocoder alloc] initWithCoordinate:koor] autorelease];
geocoder.delegate = self;
coordinate = koor;
[geocoder start];
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error {
NSLog(@"fail %@", error);
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {
self.subtitle = [placemark.addressDictionary valueForKey:@"Street"];
}
-(void)applicationWillTerminate:(UIApplication *)application {
NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
[userDef setValue:subtitle forKey:@"SavedAddress"];
[userDef setBool:YES forKey:@"Street"];
[userDef synchronize];
}
@end
mainViewController.m
-(void)viewDidLoad {
[super viewDidLoad];
NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
if ([userDef boolForKey:@"sparadKoordinat-existerar"])
{
CLLocationCoordinate2D savedCoordinate;
savedCoordinate.latitude = [userDef doubleForKey:@"sparadKoordinat-latitud"];
savedCoordinate.longitude = [userDef doubleForKey:@"sparadKoordinat-longitud"];
SparaPosition *position=[[SparaPosition alloc] initWithCoordinate:savedCoordinate];
[mapView addAnnotation:position];
savedPosition = savedCoordinate;
raderaSparad.enabled=YES;
skickaMaps.enabled=YES;
mStoreLocationButton.enabled=NO;
friZoom = NO;
NSString *savedAddress = [[NSUserDefaults standardUserDefaults] objectForKey:@"SavedAddress"];
if (savedAddress) {
savedAddress.subtitle = [userDef valueForKey:@"Street"]; // what code should I add here?
}
MKCoordinateRegion region;
region.center.latitude = savedCoordinate.latitude;
region.center.longitude= savedCoordinate.longitude;
MKCoordinateSpan span;
span.latitudeDelta = 0.01;
span.longitudeDelta = 0.01;
region.span = span;
region = [mapView regionThatFits:region];
[mapView setRegion:region animated:YES];
[mapView setRegion:region animated:TRUE];
}