带有 malloc'd 结构的 NSMutableArray addobject [英] NSMutableArray addobject with malloc'd struct
本文介绍了带有 malloc'd 结构的 NSMutableArray addobject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在处理一段代码时遇到了问题.我正在尝试使用 addObject 方法将 CLLocationCoordinate2D 的实例添加到 NSMutable 数组,但是每当执行该行时,我的应用程序就会崩溃.这段代码有什么明显的错误吗?
I'm having trouble with a snippet of code. I'm trying to add an instance of CLLocationCoordinate2D to a NSMutable array using the addObject method, but whenever the line is executed, my app crashes. Is there anything obvious wrong with this code?
崩溃就在这条线上:
[points addObject:(id)new_coordinate];
多边形.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
推荐答案
正确的做法是将数据封装在一个 NSValue
中,专门用于将 C 类型放入 NSArray
s 和其他集合.
The proper way to do this is to encapsulate the data inside a NSValue
, which is specifically for putting C types in NSArray
s and other collections.
这篇关于带有 malloc&#39;d 结构的 NSMutableArray addobject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文