2009-06-18 116 views
18

我們可以將NSArray轉換爲c數組。 。如果替代方案是不是有什麼[假設我需要養活在OpenGL函數的C組,其中C數組包含的plist文件中讀取的頂點指針]NSArray到C數組

回答

37

答案取決於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-陣列的例子,保持陣列項目作爲對象 - 對象:

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 -terminate的陣列,而不是通過左右其長度:

// 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); 
+2

這是一個偉大的答案,我希望我能投了不止一次。我確實有一個建議,即使用'NSString **'類型有點混淆。我建議使用帶有malloc返回指針的`[NSData initWithBytesNoCopy:length:freeWhenDone:]`和數組的大小。 – alfwatt 2011-09-29 20:18:59

+0

我試過使用malloc的第二種方法,我認爲它需要禁用弧。至少,這是我如何運作的。當問這個問題時,也許arc不存在...... – 2017-01-23 08:53:32

4

我會建議自己進行轉換,喜歡的東西:

NSArray * myArray; 

... // code feeding myArray 

id table[ [myArray count] ]; 

int i = 0; 
for (id item in myArray) 
{ 
    table[i++] = item; 
} 
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);