带有malloc'd结构的NSMutableArray addobject

Cod*_*eef 1 iphone cocoa-touch objective-c nsmutablearray

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

崩溃就在这条线上:

[points addObject:(id)new_coordinate];
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

Phi*_*ert 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);
Run Code Online (Sandbox Code Playgroud)

检索对象:

CLLocationCoordinate2D* c = (CLLocationCoordinate2D*) [[points objectAtIndex:0] bytes];
Run Code Online (Sandbox Code Playgroud)