1

我有一个 c-struct 数组,并且想要定义一个属性。这是相关代码..

struct Vertex {
    float x, y, z;
    float nx, ny, nz;
    float u, v;
};

@interface Mesh : NSObject{
    Vertex m_vertices[MaxVertices];
}
@property (nonatomic) Vertex m_vertices[MaxVertices];
@end

@implementation Mesh;
@synthesize m_vertices[MaxVertices];
@end

我第一次这样写是有错误的。如何使用 c-struct 数组设置属性,或自定义 setter 和 getter?任何提示将不胜感激!

4

4 回答 4

2

利用

@property (nonatomic) Vertex *m_vertices;

@synthesize m_vertices;

反而。你不能使用这样的静态数组;malloc() 它在你的构造函数中使用类似这样的东西,在析构函数中使用 free() :

- (id)init
{
    if ((self = [super init]))
    {
        m_vertices = malloc(sizeof(*m_vertices) * NUM_OF_VERTICES);
    }
    return self;
}

- (oneway void)dealloc
{
    free(m_vertices);
    [super dealloc];
}
于 2012-05-24T14:53:14.293 回答
1

您不能将数组用作属性。你可以做两件事:

1) 使用 NSArray 或 NSMutableArray 来保存对象而不是结构。

或者

2)将数组放入结构中:

typedef struct VertexArray
{
    struct Vertex m_vertices [MaxVertices];
};

@property (nonatomic, assign) VertexArray* m_vertices;

或者

3) 将数组放入对象中

@interface VertexArray
{
    struct Vertex m_vertices [MaxVertices];
}

- (struct Vertex)getVertexofIndex:(NSUInteger)index;
- (void)setVertex:(struct Vertex)vertex atIndex:(NSUInteger)index;

@end

对于 Mesh 中的属性:

@property (nonatomic, retain) VertexArray* m_vertices;

或者你可以把VertexArray的内容直接放在Mesh里面(即成员变量和两个访问器方法)。

于 2012-05-24T14:53:35.297 回答
1

这是我所能得到的接近。

typedef struct _Vertex {
float x, y, z;
float nx, ny, nz;
float u, v;
} Vertex;

#define MaxVertices 5

@interface Mesh : NSObject{
    Vertex m_verticesX[MaxVertices];
    Vertex *m_vertices;
}
@property (nonatomic) Vertex *m_vertices;
@end

@implementation Mesh;
@synthesize m_vertices;
- (Vertex *)m_vertices
{
    if (!m_vertices)
        m_vertices = m_verticesX;
    return m_vertices;
}
@end

希望能帮助到你。

于 2012-05-24T14:51:00.187 回答
0

当您在 C 中返回(任何类型)数组时,您将返回该数组的第一个索引。

因此,如果我想返回下面在接口中声明的变量。

 Vertex m_vertices[MaxVertices];

我可以说...

- (Vertex *)m_vertices
{
    return m_vertices;
}

这和上面说的一样...

- (Vertex *)m_vertices
   {
       return &m_vertices[0];
   }

但是,如果您想返回整个数组,最好的方法可能是使用 memcpy 指令。

memcpy(<#void *#>, <#const void *#>, <#size_t#>)

在此处参考:http ://www.cplusplus.com/reference/cstring/memcpy/

像这样写函数...

- (Vertex *)m_vertices
{
   Vertex *localVertex;
   memcpy(localVertex,&m_vertices,sizeof(Vertex)* MaxVertices);
   return localVertex;
}

这会复制文字字节并且非常快。它将返回整个数组。

更好的方法是尽可能地制作这样的功能。

- (Vertex *)m_vertices_nthIndex:(int)index
{
   return(&m_vertices[index]);
}

这样你就可以得到你需要的任何项目的索引。

于 2013-05-03T18:29:40.420 回答