[英]Custom property's getter and setter with c++ struct array in objective-c
我有一個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? 任何提示將不勝感激!
采用
@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];
}
這是我能得到的結果。
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
希望能幫助到你。
您不能將數組用作屬性。 你可以做兩件事:
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中(即成員變量和兩個訪問器方法)。
當您在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]);
}
這樣您就可以獲得所需項目的索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.