我遇到了一段代碼的問題。我試圖使用addObject方法將CLLocationCoordinate2D實例添加到NSMutable數組,但是每當執行該行時,我的應用就會崩潰。這段代碼有什麼明顯的錯誤嗎?帶malloc'd結構的NSMutableArray addobject
崩潰是在這條線:
[points addObject:(id)new_coordinate];
Polygon.m:
#import "Polygon.h"
@implementation Polygon
@synthesize points;
- (id)init {
self = [super init];
if(self) {
points = [[NSMutableArray alloc] init];
}
return self;
}
-(void)addPointLatitude:(double)latitude Longitude:(double)longitude {
NSLog(@"Adding Coordinate: [%f, %f] %d", latitude, longitude, [points count]);
CLLocationCoordinate2D* new_coordinate = malloc(sizeof(CLLocationCoordinate2D));
new_coordinate->latitude = latitude;
new_coordinate->longitude = longitude;
[points addObject:(id)new_coordinate];
NSLog(@"%d", [points count]);
}
-(bool)pointInPolygon:(CLLocationCoordinate2D*) p {
return true;
}
-(CLLocationCoordinate2D*) getNEBounds {
...
}
-(CLLocationCoordinate2D*) getSWBounds {
...
}
-(void) dealloc {
for(int count = 0; count < [points count]; count++) {
free([points objectAtIndex:count]);
}
[points release];
[super dealloc];
}
@end
根本就不需要malloc。你應該在棧上使用一個變量來創建和初始化你的CLLocationCoordinate2D結構,然後把它包裝在一個NSValue對象中(參見下面的subw的響應)。當從數組中移除NSValue對象時,其內存將被正確釋放。當你的堆棧變量超出範圍時,它的內存也將被回收。 – 2009-09-08 17:30:14
太棒了 - 謝謝,傑森! – Codebeef 2009-09-08 18:13:23