2009-09-08 73 views
1

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

根本就不需要malloc。你应该在栈上使用一个变量来创建和初始化你的CLLocationCoordinate2D结构,然后把它包装在一个NSValue对象中(参见下面的subw的响应)。当从数组中移除NSValue对象时,其内存将被正确释放。当你的堆栈变量超出范围时,它的内存也将被回收。 – 2009-09-08 17:30:14

+0

太棒了 - 谢谢,杰森! – Codebeef 2009-09-08 18:13:23

回答

2

这样做的正确方法是将数据封装在NSValue中,该数据专门用于将NSArray和其他集合中的C类型放入其中。

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]; 
+0

我会在今天晚些时候尝试 - 感谢Philippe! – Codebeef 2009-09-08 09:44:11

+1

准确地说,您可以将符合NSObject协议的对象添加到NSArray中。并非所有符合该要求的对象都来自NSObject。 – NSResponder 2009-09-08 11:41:39

+0

将字节放在NSData中的好处是NSData将声明malloc'd块的所有权并在释放NSData对象本身时释放它(除非使用'dataWithBytesNoCopy:')。 – 2009-09-08 15:37:12

0

您可以使用CFArrayCreateMutable功能与定制回调来创建一个可变数组不保留/释放。

相关问题