Problem with MKReverseGeocoder - iphone

For some reason, I cannot get the name of the city (locality) from my code. Please help!
- (void)viewDidLoad {
[super viewDidLoad];
self.lm = [[CLLocationManager alloc] init];
lm.delegate = self;
lm.desiredAccuracy = kCLLocationAccuracyBest;
lm.distanceFilter = kCLDistanceFilterNone;
[lm startUpdatingLocation];
}
- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation: (CLLocation *) newLocation fromLocation: (CLLocation *)oldLocation {
if (!geocoder) {
geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate];
geocoder.delegate = self;
[geocoder start];
}
NSString *lat = [[NSString alloc] initWithFormat:#"%f", newLocation.coordinate.latitude];
NSString *lng = [[NSString alloc] initWithFormat:#"%f", newLocation.coordinate.longitude];
NSString *acc = [[NSString alloc] initWithFormat:#"%f", newLocation.horizontalAccuracy];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:lat message:lng delegate:self cancelButtonTitle:acc otherButtonTitles: #"button", nil];
[alert show];
[alert release];
[lat, lng, acc release];
}
- (void) reverseGeocoder:(MKReverseGeocoder *)geo didFailWithError:(NSError *)error {
[geocoder release];
geocoder = nil;
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geo didFindPlacemark:(MKPlacemark *)placemark {
**THIS IS WHERE THE ERROR IS OCCURRING** (REQUEST FOR MEMBER 'LOCALITY' IN SOMETHING NOT A STRUCTURE OR UNION)
location = [NSString stringWithFormat:#"%#", placemark.locality];
[geocoder release];
geocoder = nil;
}

I realize that this is a relatively old question, but ...
I ran into the exact same issue and resorted to using the addressDictionary placemark attribute, e.g.,
[placemark.addressDictionary objectForKey#"City"]
instead of
placemark.subAdministrativeArea
I don't understand why the latter doesn't work either.

This error usually occurs when you are trying to access a member of a structure, but in something that is not a structure. For example:
struct {
int a;
int b;
} foo;
int fum;
fum.d = 5;
It also happens if you're trying to access an instance when you have a pointer, and vice versa. For example:
struct foo {
int x, y, z;
};
struct foo a, *b = &a;
b.x = 12; /* This will generate the error, it should be b->x or (*b).x */
It also appears if you do this:
struct foo { int x, int y, int z }foo;
foo.x=12
instead of:
struct foo { int x; int y; int z; }foo;
foo.x=12
Because then, you get a code that looks like it's dealing with instances, when in fact it's dealing with pointers.
It seems to me that you need to check on your code.
Perhaps, try this:
NSString *strLocation = (NSString *)placemark.locality; // Get locality

Related

UICGDirectionsDelegate function are not calling in iphone

i display route from start to end point in mapView in iphone and i done it.But after one day i open this project and it does not display route because UICGDirectionsDelegate functions are not called. I dont know why its happen kindly some body guide me about this problem.Many thanks and my sample code is here`
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
if (diretions.isInitialized) {
[self update];
}
routeOverlayView = [[UICRouteOverlayMapView alloc] initWithMapView:mapViews];
diretions = [UICGDirections sharedDirections];
diretions.delegate = self;
}
- (IBAction)backButton:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)update {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
UICGDirectionsOptions *options = [[UICGDirectionsOptions alloc] init];
options.travelMode = travelMode;
if (is_route) {
startPoint = [NSString stringWithFormat:#"%f,%f",APPDELEGATE.user_latitude,APPDELEGATE.user_longitude];
endPoint = [NSString stringWithFormat:#"%#,%#",routeObj.latitude,routeObj.longitude];
destination = poiObj.english_title;
}else {
startPoint = [NSString stringWithFormat:#"%f,%f",APPDELEGATE.user_latitude,APPDELEGATE.user_longitude];
endPoint = [NSString stringWithFormat:#"%# ,%#",poiObj.latitude,poiObj.longitude];
destination = routeObj.starting_poi_name;
}
[diretions loadWithStartPoint:startPoint endPoint:endPoint options:options];
}
- (void)moveToCurrentLocation:(id)sender {
[mapViews setCenterCoordinate:[mapViews.userLocation coordinate] animated:YES];
}
- (void)addPinAnnotation:(id)sender {
UICRouteAnnotation *pinAnnotation = [[UICRouteAnnotation alloc] initWithCoordinate:[mapViews centerCoordinate]
title:nil
annotationType:UICRouteAnnotationTypeWayPoint];
[mapViews addAnnotation:pinAnnotation];
}
#pragma mark <UICGDirectionsDelegate> Methods
- (void)directionsDidFinishInitialize:(UICGDirections *)directions {
[self update];
}
- (void)directions:(UICGDirections *)directions didFailInitializeWithError:(NSError *)error {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Map Directions" message:[error localizedFailureReason] delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alertView show];
}
- (void)directionsDidUpdateDirections:(UICGDirections *)directions {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
// Overlay polylines
UICGPolyline *polyline = [directions polyline];
NSArray *routePoints = [polyline routePoints];
[routeOverlayView setRoutes:routePoints];
// Add annotations
currentLocation = #"You are here";
UICRouteAnnotation *startAnnotation = [[UICRouteAnnotation alloc] initWithCoordinate:[[routePoints objectAtIndex:0] coordinate]
title:currentLocation
annotationType:UICRouteAnnotationTypeStart];
UICRouteAnnotation *endAnnotation = [[UICRouteAnnotation alloc] initWithCoordinate:[[routePoints lastObject] coordinate]
title:destination
annotationType:UICRouteAnnotationTypeEnd];
[mapViews addAnnotations:[NSArray arrayWithObjects:startAnnotation, endAnnotation, nil]];
}
- (void)directions:(UICGDirections *)directions didFailWithMessage:(NSString *)message {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Map Directions" message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alertView show];
}
`
In UICGRoute.m
Replace this
NSArray *stepDics;
NSDictionary *k;
for (int i = 0; i<allKeys.count; i++) {
k = [dictionaryRepresentation objectForKey:[allKeys objectAtIndex:i]];
if ([k objectForKey:#"Steps"]) {
stepDics = [k objectForKey:#"Steps"];
break;
}
}
with
NSDictionary *k = [dictionaryRepresentation objectForKey:[allKeys objectAtIndex:[allKeys count] - 1]];
NSArray *stepDics = [k objectForKey:#"Steps"];

Memory-management in iOS Programming

I have a little problem with memory management in my iOS App. I load an XML and set all Values in this XML to Spezific Objects. Now my problem is when i reload the XML every 15 - 20 reloads of this XML my app Crash on Parsing here is a sample of my parser.
EDIT: Here ist the ERROR when NSZombie is Enabled if NSZombie is disabled I didn't get an ERROR message.
-[CFNumber retain]: message sent to deallocated instance
thanks for help.
EDIT:
the beginning of my Code:
- (id)init
{
self = [super init];
if (self) {
TheObjects *theObjects = [[TheObjects alloc] init];
[self parse];
}
return self;
}
- (void) reload{
reload = YES;
TheObjects *theTmpObjects = [[TheObjects alloc] init];
[self parse];
}
- (void)parse{
for (id xmlOBject in xmlObjects){
MyObject *object = [[MyObject alloc] init];
object.number1 = [NSNumber numberWithInt:1];
object.number2 = [NSNumber numberWithInt:2];
object.number3 = [NSNumber numberWithInt:3];
if (reload)
[theTmpObjects.objects addObject:object];
else
[theObjects.objects addObject:object];
[object release];
}
//later in my code
TheObjects *localTheTmpObjects = nil;
if (reload){
localTheTmpObjects = theObjects;
theObjects = theTmpObjects;
}
if ([delegate respondsToSelector:#selector(finished:)]){
[delegate performSelector:#selector(finished:) withObject:theObjects];
}
if(reload)
[localTheTmpObjects release];
}
remove the line [localTheTmpObjects release]
you don't own the object
at the end, call the `[localTheTmpObjects autorelease];`
this is because if you release array, all its objects are released and hence may cause crash, when your array may in use
- (id)init
{
self = [super init];
if (self) {
TheObjects *obbjects = [[TheObjects alloc] init];
theObjects = objects;
[objects releas];
[self parse];
}
return self;
}
- (void) reload{
reload = YES;
TheObjects *obbjects = [[TheObjects alloc] init];
thetmpObjects = objects;
[objects releas]; [self parse];
}
- (void)parse{
for (id xmlOBject in xmlObjects){
MyObject *object = [[MyObject alloc] init];
object.number1 = [NSNumber numberWithInt:1];
object.number2 = [NSNumber numberWithInt:2];
object.number3 = [NSNumber numberWithInt:3];
if (reload)
[theTmpObjects.objects addObject:object];
else
[theObjects.objects addObject:object];
[object release];
}
//later in my code
TheObjects *localTheTmpObjects = nil;
if (reload){
localTheTmpObjects = theObjects;
theObjects = theTmpObjects;
}
if ([delegate respondsToSelector:#selector(finished:)]){
[delegate performSelector:#selector(finished:) withObject:theObjects];
}
}

Using a variable declared somewhere else in a different method

I just started coding in Objective C, and am making an app that will track the users location, and send an alert with the latlng in it. This code isn't complete in the slightest, but I ran into a problem with trying to use the variable I created "lat" in the "viewDidLoad" for the alert. I declared the variable in the CLLocationManager delegate/method(I don't really know what it's called) and I don't know how to use it in other places.
- (void)viewDidLoad
{
locationManager =[[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = 100.0f;
[locationManager startUpdatingLocation];
UIAlertView *message = [[UIAlertView alloc] initWithTitle: #"Your current Latitude is:"
message:This is where I want to put the variable "lat"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[message show];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(void) locationmanager: (CLLocationManager *) manager
didUpdateToLocation: (CLLocation *) newLocation
fromLocation: (CLLocation *) oldLocation
{
NSString *lat = [[NSString alloc] initWithFormat: #"%g",newLocation.coordinate.latitude];
NSString *lng = [[NSString alloc] initWithFormat:#"%g", newLocation.coordinate.longitude];
}
Any help would be appreciated!
Simple solution.
Your ViewController .h should look something like this
#interface ViewController : UIViewController {
NSString *lat;
NSString *lng;
}
then this becomes
-(void) locationmanager: (CLLocationManager *) manager
didUpdateToLocation: (CLLocation *) newLocation
fromLocation: (CLLocation *) oldLocation
{
lat = [[NSString alloc] initWithFormat: #"%g",newLocation.coordinate.latitude];
lng = [[NSString alloc] initWithFormat:#"%g", newLocation.coordinate.longitude];
NSLog(lat);
NSLog(lng);
}
NSlog simple out puts to the console which is locate just below where you code
remove
UIAlertView *message = [[UIAlertView alloc] initWithTitle: #"Your current Latitude is:"
message:This is where I want to put the variable "lat"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[message show];
Because that will just show an alert as soon as the view is loaded
Hope this helps

[CFDictionary count]: message sent to deallocated instance

My app is calling the rqst_run method below in didViewLoad method but I've an error. Debugger reports the following error:
[CFDictionary count]: message sent to deallocated instance
and debug marker is placed on this line (in tableView numberOfRowsInSection method below):
if([self.listing_items count] > 0)
I don't know where this variable get released
Declared in header file (interface section):
NSMutableString *rqst_error;
NSMutableData *rqst_data;
NSMutableDictionary *listing_items;
and I defined this method in implementation:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if([self.listing_items count] > 0)
{
if([self.listing_items objectForKey:#"items"])
{
return [[self.listing_items objectForKey:#"items"] count];
}
}
}
- (void)rqst_run
{
rqst_data = [[NSMutableData data] retain];
NSMutableURLRequest *http_request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.feedserver.com/request/"]];
[http_request setHTTPMethod:#"POST"];
NSString *post_data = [[NSString alloc] initwithFormat:#"param1=%#&param2=%#&param3=%#",rqst_param1,rqst_param2,rqst_param3];
[http_request setHTTPBody:[post_data dataUsingEncoding:NSUTF8StringEncoding]];
rqst_finished = NO;
[post_data release];
NSURLConnection *http_connection = [[NSURLConnection alloc] initWithRequest:http_request];
[http_request release];
if(http_connection)
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
if([rqst_data length]>0)
{
NSString *rqst_data_str = [[NSString alloc] rqst_data encoding:NSUTF8StringEncoding];
SBJsonParser *json_parser = [[SBJsonParse alloc] init];
id feed = [json_parser objectWithString:rqst_data_str error:nil];
listing_items = (NSMutableDictionary *)feed;
[json_parser release];
[rqst_data_str release];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Feed" message:#"No data returned" delegate:self cancemButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Connection Problem" message:#"Connection to server failed" delegate:self cancemButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[rqst_data setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[rqst_data appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[rqst_data release];
[connection release];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[rqst_data release];
[connection release];
rqst_finished = YES;
}
NSMutableDictionary must be properly initialized before use. In your code you assign feed to listing_items and then release it. It haven't been retained so listing_items is also removed.
Try to init dictionary like this:
listing_items = [[NSMutableDictionary alloc] initWithDictionary:feed];
and all should work fine.
Instead of this
listing_items = (NSMutableDictionary *)feed;
Use this
self.listing_items = [NSMutableDictionary dictionaryWithDictionary:feed];
It's pretty clear that:
* You use the instance variable instead of the property to assign the value to listing_items
* You put an autoreleased value in this ivar.
listing_items = (NSMutableDictionary *)feed; is clearly your error because feed is an autorleased variable (and then will be deallocated at the end of the current runloop by definition.
Either declare a #property(retain) for listing_items and use it each time you want to assign (autoreleased) value to it (so that the property will manage the retain/release on assignation)
Or retain the stored value manually (but this is painful as you need not to forget to release the previous value before assigning a new one to listing_items each time... which is what the setter method does when called either directly or thru the property assignment)
i think you need to initialize your NSMutableDictionary. Right now its just a pointer pointing to feed. when feed gets released, it just points to nil.
in the viewDidLoad :
listing_items = [[NSMutableDictionary alloc] init];
or you need to retain the data:
listing_items = [(NSMutableDictionary *)feed retain];
SBJsonParser *json_parser = [[SBJsonParse alloc] init];
id feed = [json_parser objectWithString:rqst_data_str error:nil];
listing_items = (NSMutableDictionary *)feed;
[json_parser release];
When you release the json_parser, the dictionary it holds is released too.
So, as others said, you need to retain the dictionary obtained from json_parser.

iPhone GPS problem simulator doesn't react

I am trying to create simple GPS application just to display simple data in simulator. I have no errors just cant obtain data. "didFailWithError" method is the only I can get to work :), this is the code:
- (void)viewDidLoad
{
[super viewDidLoad];
lm = [[CLLocationManager alloc] init];
if([CLLocationManager locationServicesEnabled])
{
lm.delegate = self;
lm.desiredAccuracy = kCLLocationAccuracyBest;
//lm.distanceFilter = 1000.0f;
[lm startUpdatingLocation];
}
}
- (void) locationManager: (CLLocationManager *) manager
didUpdateToLocation: (CLLocation *) newLocation
fromLocation: (CLLocation *) oldLocation{
NSString *lat = [[ NSString alloc] initWithFormat:#"%g", newLocation.coordinate.latitude];
txtLatitude.text = lat;
NSString *lng = [[NSString alloc] initWithFormat:#"%g", newLocation.coordinate.longitude];
txtLongitude.text = lng;
NSString *acc = [[NSString alloc] initWithFormat:#"%g", newLocation.horizontalAccuracy];
txtAccuracy.text = acc;
[acc release];
[lat release];
[lng release];
}
- (void) locationManager:(CLLocationManager *)manager
didFailWithError: (NSError *) error
{
NSString *msg = [[NSString alloc] initWithString:#"Error obtaining location"];
UIAlertView *alert = [[ UIAlertView alloc] initWithTitle:#"Error"
message:msg
delegate:nil
cancelButtonTitle:#"Done"
otherButtonTitles:nil];
[alert show];
[msg release];
[alert release];
}
It doesnt move ever in the simulator.
http://developer.apple.com/library/ios/#documentation/Xcode/Conceptual/iphone_development/125-Using_iPhone_Simulator/iphone_simulator_application.html
"Core Location Functionality
The relocation reported by the CoreLocation framework in the simulator is fixed at the following coordinates (accuracy 100 meters), which correspond to 1 Infinite Loop, Cupertino, CA 95014.
Latitude: 37.3317 North
Longitude: 122.0307 West"
You could try adding a simple random or timed event which pings the didUpdate... method explicitly with fake data of your preference.