Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EXC_BAD_ACCESS (code=1) Error in Xcode

I know this error has something to do with memory management but i must admit i'm stumped! Been programming in objective c for about 3 weeks and all this managing memory stuff is confusing! What is basically happening is that i have this mapview in a tableview. When clicking the back button to leave the mapview and return to the main menu i get the error above. Here is the code from the Header file

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>

@interface MapViewController : UIViewController <MKMapViewDelegate> {

    IBOutlet MKMapView* mapView;
    BOOL locate;

}

@property (nonatomic, retain) IBOutlet MKMapView* mapView;

@end

and the Implementation file

#import "MapViewController.h"

@implementation MapViewController

@synthesize mapView;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

    mapView = [[MKMapView alloc] initWithFrame:self.view.frame];
    mapView.delegate=self;
    mapView.showsUserLocation = YES;

    [self.view addSubview:mapView];

    [self.mapView.userLocation addObserver:self
                                forKeyPath:@"location"
                                   options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld)
                                   context:nil];
    locate = YES;

}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{

    if (locate == YES) {
    MKCoordinateRegion region;
    region.center = self.mapView.userLocation.coordinate;

    MKCoordinateSpan span;
    span.latitudeDelta  = 0.1; 
    span.longitudeDelta = 0.1;
    region.span = span;

    [self.mapView setRegion:region animated:YES];
        locate = NO;
    }

}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}
- (void)dealloc {
    [super dealloc];
    [mapView release];
    [self.mapView.userLocation removeObserver:self forKeyPath:@"location"];
    [self.mapView removeFromSuperview];
    self.mapView = nil;
}

@end

Can anybody shed some light for me? :)

like image 887
Craig Avatar asked Aug 30 '12 13:08

Craig


1 Answers

[super dealloc]; must be the last call in dealloc

also after [mapView release]; mapView might be gone already.

try

- (void)dealloc {

    [self.mapView.userLocation removeObserver:self forKeyPath:@"location"];
    [self.mapView removeFromSuperview];
    [mapView release];
    self.mapView = nil; 
    [super dealloc];  // at this point self — that is the same object as super — is not existent anymore
}
like image 64
vikingosegundo Avatar answered Nov 14 '22 23:11

vikingosegundo