我正在寫一個iPhone應用程序,用戶應該能夠打開並關閉地圖上的所有引腳。把所有的引腳在地圖上使用:EXC_BAD_ACCESS,同時刪除MKAnnotations
-(void) putAllPins {
for (id key in myDictionary) { //A NSDictionary
NSArray *data = [myDictionary objectForKey:key];
[self putPin: data];
}
isShowingAllPins = TRUE;
}
-(CLLocationCoordinate2D) putPin:(NSArray *) data {
NSNumber *lat = [data objectAtIndex:0];
NSNumber *lon = [data objectAtIndex:1];
NSString *name = [data objectAtIndex:2];
NSString *info = [data objectAtIndex:3];
CLLocationCoordinate2D coords = {[lat doubleValue], [lon doubleValue]};
MyMapAnnotation *annotation = [[MyMapAnnotation alloc] initWithCoordinate:coords andName:name andInformation:info];
[_mapView addAnnotation:annotation];
[annotation release];
return coords;
}
要刪除他們,我用:
-(void) removeAllPins {
NSMutableArray *toRemove = [NSMutableArray arrayWithCapacity:([_mapView.annotations count] - 1)];
for (id annotation in _mapView.annotations) {
if (annotation != _mapView.userLocation) {
[toRemove addObject:annotation];
}
}
[_mapView removeAnnotations:toRemove];
}
它工作正常,一旦刪除所有的引腳並重新添加他們。但是,一旦我第二次刪除它們,我會得到一個EXC_BAD_ACCESS錯誤。我已經將問題追溯到我的註釋類中的dealloc方法,但仍然不知道該怎麼做。任何幫助表示讚賞!
MyAnnotation.m:
@implementation MyAnnotation
@synthesize coordinate = _coordinate;
-(id) initWithCoordinate:(CLLocationCoordinate2D)coordinate andName:(NSString *)name andInformation:(NSString *)info {
self = [super init];
_coordinate = coordinate;
_name = name;
_info = info;
return self;
}
-(NSString *)title {
return [NSString stringWithFormat:@"PREFIX %@", _name];
}
-(NSString *)subtitle {
return _info;
}
- (void)dealloc {
[_name release];
[_info release];
[super dealloc];
}
@end
嗯,_name和_info從來沒有保留,這應該意味着dealloc方法根本不應該存在,我猜?刪除後,一切正常。感謝您指出這一點! – 2010-07-28 00:07:56
不完全。什麼是確保這些字符串不會在你的類下被釋放?正常的事情是保留它們,如果你想稍後發送消息給它們並釋放dealloc。你只需要確保平衡保留/釋放。 – 2010-07-28 01:31:04