在objective-c中声明双数组

时间:2013-08-21 18:41:51

标签: objective-c

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

如何使用objective-c?

执行此操作

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

Map的init:

-(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;
}

虽然发生了一些奇怪的事情。当我从创建地图的对象打印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;

但它仍然无效。

编辑:感谢您的所有答案。这最终成为我的最终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;
}

2 个答案:

答案 0 :(得分:7)

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

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

// to free when not used any more
free(tempxpoints);

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

NSMutableArray *tempxpoints = [[NSMutableArray alloc] init];
[tempxpoints addObject:@2]; // wrap the double in an NSNumber object

答案 1 :(得分:3)

如果你完全是关于它的Objective-C,那么你使用NSArray,用NSNumber填充它,并且永远不要指定长度。您通常可以给出关于可能需要多少空间的提示,但Objective-C的集合总是动态调整大小。

从最新版本的编译器开始,您可以在array[x]上使用NSArray表示法,并将直接NSNumber常量写为例如@4.5f @property(nonatomic, readonly) double * xpoints;如果这会使交易变得更加甜蜜。

如果你真的想要C风格的数组,那么你需要下降到C级思想。所以,像:

-(id)initWithXpoints:(double[]) xpointss Ypoints:(double[]) ypointss Npoints:(int)npointss { self = [super init]; if (self){ size_t sizeOfArraysInBytes = sizeof(double)*npointss; _xpoints = (double *)malloc(sizeOfArraysInBytes); memcpy(_xpoints, xpointss, sizeOfArraysInBytes); /* ... etc ... */ /* you never use self. notation in an init because it's a method call, and method calls on objects that are not yet fully instantiated aren't safe. Sample cause of failure: a subclass overrides the setter */ } return self; } - (void)dealloc { free(_xpoints); /* ... etc ... */ }

class.xpoints[0]

数组本身将在其他地方读/写(它的指针是只读的,而不是指向它的东西),如{{1}}等。