2009-09-08 65 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功能與定製回調來創建一個可變數組不保留/釋放。

相關問題