NSMutableArray addobject with malloc'd struct [英] NSMutableArray addobject with malloc'd struct

查看:132
本文介绍了NSMutableArray addobject with malloc'd struct的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



崩溃是在这一行:

 code> [points addObject:(id)new_coordinate]; 

Polygon.m:

  #importPolygon.h

@implementation多边形
@synthesize points;

- (id)init {
self = [super init];
if(self){
points = [[NSMutableArray alloc] init];
}
return self;
}


- (void)addPointLatitude:(double)latitude经度:(double)longitude {
NSLog(@添加坐标:[%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 中,这是专门用于将 NSArray s和其他集合。


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?

The crash is on this line:

[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

解决方案

The proper way to do this is to encapsulate the data inside a NSValue, which is specifically for putting C types in NSArrays and other collections.

这篇关于NSMutableArray addobject with malloc'd struct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆