5

我知道这个错误与内存管理有关,但我必须承认我很难过!在目标 c 中编程大约 3 周,所有这些管理内存的东西都令人困惑!基本上发生的事情是我在表格视图中有这个地图视图。单击后退按钮离开地图视图并返回主菜单时,我收到上述错误。这是头文件中的代码

#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

任何人都可以为我解释一下吗?:)

4

2 回答 2

12

[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
}
于 2012-08-30T13:22:49.033 回答
0

此错误也可能是由不兼容的 API 引起的(例如,您为 iOS 6.0 构建,但使用了仅在 iOS >= 8.2 中引入的方法)

于 2016-02-02T22:00:16.193 回答