gpt4 book ai didi

objective-c - Xcode 中的 EXC_BAD_ACCESS (code=1) 错误

转载 作者:可可西里 更新时间:2023-11-01 04:19:11 25 4
gpt4 key购买 nike

我知道这个错误与内存管理有关,但我必须承认我被难住了!用 objective c 编程大约 3 周,所有这些管理内存的东西都很困惑!基本上发生的是我在表格 View 中有这个 map View 。当单击后退按钮离开 map View 并返回主菜单时,出现上述错误。这是头文件中的代码

#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
}

关于objective-c - Xcode 中的 EXC_BAD_ACCESS (code=1) 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12197839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com