在objective-c中声明双数组

HSN*_*SNN 2 objective-c

我的地图对象有一组坐标.它并不总是具有相同数量的坐标.在java中我只是声明对象,Double[] xpoints并在实例化这样的地图时设置它的大小:xpoints = new double[npoints];

我如何用objective-c做到这一点?

我试过这样做:@property(nonatomic) double * xpoints;但是当我用NSLog打印它时,它的所有值都会变为0.

地图的初始化:

-(id)initWithXpoints:(double[]) xpointss Ypoints:(double[]) ypointss Npoints:(int)npointss
{
    self = [super init];
    if (self)
    {
        self.xpoints = xpointss;
        self.ypoints = ypointss;
        self.npoints = npointss;
    }
    return self;
}
Run Code Online (Sandbox Code Playgroud)

虽然发生了一些奇怪的事情.当我从创建地图的对象打印xpoints [0]时,值将更改为零.我第一次打印它有效.第二次它只打印零.

我认为这是因为发送到init的xpointss已从内存中删除.如果它是指针,我如何"实例化"xpoints属性?

有一个更好的方法吗?

补充:我尝试创建一个像这样的临时xpoints:

double tempxpoints[npointss];
double tempypoints[npointss];
for (int i = 0; i < npointss; i++)
{
    tempxpoints[i] = xpointss[i];
    tempypoints[i] = ypointss[i];
}
self.xpoints = tempxpoints;
self.ypoints = tempypoints;
Run Code Online (Sandbox Code Playgroud)

但它仍然没有奏效.

编辑:谢谢你的所有答案.这最终成为我的最终Init代码:

-(id)initWithXpoints:(double[]) xpointss Ypoints:(double[]) ypointss Npoints:(int)npointss
{
    self = [super init];
    if (self)
    {
         _xpoints = [[NSMutableArray alloc] init];
         _ypoints = [[NSMutableArray alloc] init];
         for (int i = 0; i < npointss; i++)
         {
             NSNumber *tempx = [NSNumber numberWithDouble:xpointss[i]];
             NSNumber *tempy = [NSNumber numberWithDouble:ypointss[i]];
             [_xpoints addObject:tempx];
             [_ypoints addObject:tempy];
         }
         _npoints = npointss;
    }
    return self;
}
Run Code Online (Sandbox Code Playgroud)

all*_*rog 7

如果将数组分配为局部变量,则它们将在堆栈上分配.当执行离开函数时,这些内存区域被释放.您必须使用malloc()分配可以传递的数组并使用free()它们来释放它们.

// to allocate
double[] tempxpoints = (double[])malloc(sizeof(double) * npointss);

// to free when not used any more
free(tempxpoints);
Run Code Online (Sandbox Code Playgroud)

但实际上NSArray是为处理这些案件而设计的.使用ARC,您甚至不必关心释放内存.

NSMutableArray *tempxpoints = [[NSMutableArray alloc] init];
[tempxpoints addObject:@2]; // wrap the double in an NSNumber object
Run Code Online (Sandbox Code Playgroud)