【问题标题】:How to declare a C Array as a property of an Objective-C object?如何将 C 数组声明为 Objective-C 对象的属性?
【发布时间】:2009-10-11 03:56:39
【问题描述】:

我无法将 C 数组声明为 Objective-C 属性(您知道 @property 和 @synthesize,因此我可以使用点语法)...它只是一个 3 维 int 数组..

【问题讨论】:

  • 您的阵列是否具有众所周知的大小?你现在怎么样了,你遇到了什么问题?
  • 这只是一个简单的 3-dim int 数组,就像您的答案中的数组一样。我将其声明为 @property (nonatomic, assign) int myArray[_NUM1][_NUM1][3];在 .h 和 @synthesize myArray[_NUM1][_NUM1][3] 中实现。
  • 明白了。你不能这样做,@property 仅适用于标量类型。您可以使用 @property (nonatomic, assign) int ***myArray;如果你想。对我来说,这听起来像是内存泄漏的秘诀。

标签: iphone c arrays uikit nsobject


【解决方案1】:

您不能——数组不是 C 中的左值。您必须改为声明一个指针属性并依赖使用正确数组边界的代码,或者改为使用 NSArray 属性。

例子:

@interface SomeClass
{
    int width, height, depth;
    int ***array;
}

- (void) initWithWidth:(int)width withHeight:(int)height withDepth:(int)depth;
- (void) dealloc;

@property(nonatomic, readonly) array;
@end

@implementation SomeClass

@synthesize array;

 - (void) initWithWidth:(int)width withHeight:(int)height withDepth:(int)depth
{
    self->width  = width;
    self->height = height;
    self->depth  = depth;
    array = malloc(width * sizeof(int **));
    for(int i = 0; i < width; i++)
    {
        array[i] = malloc(height * sizeof(int *));
        for(int j = 0; j < height; j++)
            array[i][j] = malloc(depth * sizeof(int));
    }
}

- (void) dealloc
{
    for(int i = 0; i < width; i++)
    {
        for(int j = 0; j < height; j++)
            free(array[i][j]);
        free(array[i]);
    }
    free(array);
}

@end

然后您可以将array 属性用作3 维数组。

【讨论】:

  • 正确,但我发现使用单个分配然后进行一些简单的数学运算来访问数组中的元素就好像它是多维的一样更简单。这在内存使用方面往往更有效(假设您不稀疏)。
猜你喜欢
  • 2014-03-21
  • 1970-01-01
  • 2015-11-12
  • 2012-06-16
  • 2013-10-04
  • 1970-01-01
  • 2011-01-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多