添加注释时Gettin Bad Access

时间:2013-11-18 08:35:24

标签: ios iphone objective-c xcode

我试图在我的Mapview中添加许多注释(取决于我的数组中有多少个对象),如下所示:

-(void)viewWillAppear:(BOOL)animated
{
[mapView removeAnnotations:mapView.annotations];

for (Daten *info in datenArray) {
    CLLocationCoordinate2D location;
    location.latitude = (double)[info.lati doubleValue];
    location.longitude = (double)[info.longi doubleValue];
    MapPin *newAnnotation =[[[MapPin alloc] initWithTitle:info.rating andCoordinate:location] autorelease];
    [mapView addAnnotation:newAnnotation];
}

[self zoomToFitMapAnnotations:self.mapView];
[self.mapView selectAnnotation:self.mapView.annotations.lastObject animated:YES];

}

我第一次切换到该视图时效果很好......但如果我第二次来到这个视图,我会收到错误的错误访问:

*** -[CFString length]: message sent to deallocated instance 0x17e140c0

编辑:

这就是我的MapPin类:

@interface MapPin : NSObject <MKAnnotation> {

NSString *title;
NSString *subtitle;
CLLocationCoordinate2D coordinate;

}

@property (nonatomic, copy) NSString *title;
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic, readonly, copy) NSString *subtitle;

- (id)initWithTitle:(NSString *)ttl andCoordinate:(CLLocationCoordinate2D)c2d;

EDIT2:

Exception

EDIT3:

以下是实施:

#import "MapPin.h"

@implementation MapPin
@synthesize title, coordinate, subtitle;

- (id)initWithTitle:(NSString *)ttl andCoordinate:(CLLocationCoordinate2D)c2d {
[super init];
subtitle = ttl;
title = @"Rating:";
coordinate = c2d;
return self;
}

- (void)dealloc {
[title release];
[subtitle release];
[super dealloc];
}

@end

1 个答案:

答案 0 :(得分:0)

您应该在init中为对象发送保留或复制消息。

 if (self = [super init]) {
 subtitle = [ttl copy];
 title = [@"Rating:" retain]
 ...
 }
 return self;

@"Rating:"是创建自动释放对象的等同方法。

或者您可以使用self.title = @"Rating:";