带有malloc'd结构的NSMutableArray addobject

时间:2009-09-08 09:16:47

标签: iphone objective-c cocoa-touch nsmutablearray

我遇到一段代码问题。我正在尝试使用addObject方法将一个CLLocationCoordinate2D实例添加到NSMutable数组,但每当执行该行时,我的应用程序崩溃。这段代码有什么明显的错误吗?

崩溃就在这条线上:

[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

3 个答案:

答案 0 :(得分:6)

您只能将NSObject派生的对象添加到数组中。您应该将数据封装在适当的对象中(例如NSData)。

例如:

CLLocationCoordinate2D* new_coordinate = malloc(sizeof(CLLocationCoordinate2D));
    new_coordinate->latitude = latitude;
    new_coordinate->longitude = longitude;
    [points addObject:[NSData dataWithBytes:(void *)new_coordinate length:sizeof(CLLocationCoordinate2D)]];
    free(new_coordinate);

检索对象:

CLLocationCoordinate2D* c = (CLLocationCoordinate2D*) [[points objectAtIndex:0] bytes];

答案 1 :(得分:2)

执行此操作的正确方法是将数据封装在NSValue内,这专门用于将C类型放入NSArray s和其他集合中。

答案 2 :(得分:0)

您可以将CFArrayCreateMutable函数与自定义回调一起使用来创建不保留/释放的可变数组。