我遇到了一段代码的问题。我试图使用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