NSArray到C数组

时间:2009-06-18 09:25:34

标签: cocoa opengl

我们可以将NSArray转换为c数组。如果不是有什么替代方案。[假设我需要在opengl函数中提供c数组,其中c数组包含从plist文件读取的顶点指针]

3 个答案:

答案 0 :(得分:38)

答案取决于C阵列的性质。

如果你需要填充原始值和已知长度的数组,你可以这样做:

NSArray* nsArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],
                                             [NSNumber numberWithInt:2],
                                             nil];
int cArray[2];

// Fill C-array with ints
int count = [nsArray count];

for (int i = 0; i < count; ++i) {
    cArray[i] = [[nsArray objectAtIndex:i] intValue];
}

// Do stuff with the C-array
NSLog(@"%d %d", cArray[0], cArray[1]);

以下是我们想要从NSArray创建新C数组的示例,将数组项保留为Obj-C对象:

NSArray* nsArray = [NSArray arrayWithObjects:@"First", @"Second", nil];

// Make a C-array
int count = [nsArray count];
NSString** cArray = malloc(sizeof(NSString*) * count);

for (int i = 0; i < count; ++i) {
    cArray[i] = [nsArray objectAtIndex:i];
    [cArray[i] retain];    // C-arrays don't automatically retain contents
}

// Do stuff with the C-array
for (int i = 0; i < count; ++i) {
    NSLog(cArray[i]);
}

// Free the C-array's memory
for (int i = 0; i < count; ++i) {
    [cArray[i] release];
}
free(cArray);

或者,您可能希望nil - 终止数组而不是传递其长度:

// Make a nil-terminated C-array
int count = [nsArray count];
NSString** cArray = malloc(sizeof(NSString*) * (count + 1));

for (int i = 0; i < count; ++i) {
    cArray[i] = [nsArray objectAtIndex:i];
    [cArray[i] retain];    // C-arrays don't automatically retain contents
}

cArray[count] = nil;

// Do stuff with the C-array
for (NSString** item = cArray; *item; ++item) {
    NSLog(*item);
}

// Free the C-array's memory
for (NSString** item = cArray; *item; ++item) {
    [*item release];
}
free(cArray);

答案 1 :(得分:6)

NSArray有一个-getObjects:range:方法,用于为数组的子范围创建C数组。

示例:

NSArray *someArray = /* .... */;
NSRange copyRange = NSMakeRange(0, [someArray count]);
id *cArray = malloc(sizeof(id *) * copyRange.length);

[someArray getObjects:cArray range:copyRange];

/* use cArray somewhere */

free(cArray);

答案 2 :(得分:4)

我建议改变自己,比如:

NSArray * myArray;

... // code feeding myArray

id table[ [myArray count] ];

int i = 0;
for (id item in myArray)
{
    table[i++] = item;
}