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);
3条答案
按热度按时间2uluyalo1#
答案取决于C数组的性质。
如果需要填充已知长度的原始值数组,可以执行以下操作:
下面是一个示例,我们希望从
NSArray
创建一个新的C数组,并将数组项保留为Obj-C对象:或者,您可能希望
nil
终止数组,而不是传递其长度:57hvy0tb2#
NSArray
有一个-getObjects:range:
方法,用于为数组的子范围创建C数组。示例:
unhi4e5o3#
我建议你改变自己的信仰,比如: