代码之家  ›  专栏  ›  技术社区  ›  Codebeef

具有malloc'd结构的nsmutableray addobject

  •  1
  • Codebeef  · 技术社区  · 15 年前

    我在一段代码上遇到了麻烦。我正在尝试使用addObject方法将cllocationCoordinate2d的实例添加到NSmutable数组中,但每当执行该行时,我的应用程序就会崩溃。这个代码有什么明显的错误吗?

    车祸发生在这条线上:

    [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
    
    3 回复  |  直到 15 年前
        1
  •  2
  •   mrueg    15 年前

    正确的方法是将数据封装在 NSValue ,专门用于将C类型放入 NSArray S和其他收藏。

        2
  •  6
  •   Philippe Leybaert    15 年前

    只能将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];
    
        3
  •  0
  •   rpetrich    15 年前

    您可以使用 CFArrayCreateMutable 函数与自定义回调一起创建不保留/释放的可变数组。