NSArray到C数组

gstyhher  于 2022-10-18  发布在  其他
关注(0)|答案(3)|浏览(114)

我们可以将NS数组转换为C数组吗?
如果不是,还有其他选择吗?假设我需要将C数组提供给OpenGL函数,其中C数组包含从plist文件读取的顶点指针。

2uluyalo

2uluyalo1#

答案取决于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);
57hvy0tb

57hvy0tb2#

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);
unhi4e5o

unhi4e5o3#

我建议你改变自己的信仰,比如:

NSArray * myArray;

... // code feeding myArray

id table[ [myArray count] ];

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

相关问题