NSArray到C数组 [英] NSArray to C array
问题描述
我们可以将NSArray转换为c数组。如果没有什么替代品有那里。[假设我需要在opengl函数中提供c数组,其中c数组包含从plist文件读取的顶点指针]
can we convert NSArray to c array. if not what alternatives are there.[suppose i need to feed the c array in opengl functions where the c array contains vertex pointer read from plist files]
推荐答案
答案取决于C数组的性质。
The answer depends on the nature of the C-array.
如果你需要填充一个原始值数组,做这样的事情:
If you need to populate an array of primitive values and of known length, you could do something like this:
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
,将数组项目保留为Obj-C对象:
Here's an example where we want to create a new C-array from an NSArray
, keeping the array items as Obj-C objects:
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
终止数组而不是传递其长度:
Or, you might want to nil
-terminate the array instead of passing its length around:
// 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);
这篇关于NSArray到C数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!