[英]EXC_BAD_ACCESS code=2 error on custom class initialization in Xcode
[英]EXC_BAD_ACCESS (code=1) Error in Xcode
我知道這個錯誤與內存管理有關,但我必須承認我很難過! 在目標c中編程大約3周,所有這些管理內存的東西都令人困惑! 基本上發生的是我在tableview中有這個mapview。 單擊后退按鈕離開mapview並返回主菜單時,我得到上面的錯誤。 這是Header文件中的代碼
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface MapViewController : UIViewController <MKMapViewDelegate> {
IBOutlet MKMapView* mapView;
BOOL locate;
}
@property (nonatomic, retain) IBOutlet MKMapView* mapView;
@end
和實施文件
#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
有人可以為我揭開光明嗎? :)
[super dealloc];
必須是dealloc
的最后一次調用
也是在[mapView release];
mapView可能已經消失了。
嘗試
- (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
}
此錯誤也可能由不兼容的API引起(例如,您為iOS 6.0構建,但使用僅在iOS> = 8.2中引入的方法)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.