你會希望做一些動態內存,你可以不依賴UTF8String的後備內存正在發佈。
NSArray *strings = @[ @"String 1", @"Other string", @"Random String"];
char **cStrings = NULL;
NSInteger numCStrings = strings.count;
if (numCStrings) {
cStrings = (char **)calloc(numCStrings, sizeof(char*)) ;
if (cStrings) {
// Safer to allocate memory for each string
for (NSInteger i=0;i<numCStrings;i++) {
NSString *nsString = strings[i];
char *cString = (char *)malloc([nsString lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1); // + 1 for \0
if (cString) {
strcpy(cString, nsString.UTF8String);
cStrings[i] = cString;
} else {
// You should handle your error
}
}
} else {
// You should handle your error
}
}
for (NSInteger i=0;i<numCStrings;i++) {
NSLog(@"C-String (%ld): %s", i, cStrings[i]);
}
// Note you need to free your memory later!
// Do any additional setup after loading the view, typically from a nib.
for (NSInteger i=0;i<numCStrings;i++) {
if (cStrings[i]) {
// Free each string
free(cStrings[i]);
}
}
// Free the array
free(cStrings);
cStrings = NULL;
numCStrings = 0;
C API會改變字符串的內容嗎? – kennytm
我不這麼認爲,但理論上可以。 – zeroimpl
如果是這樣,沒有什麼會改變原來的NSArray。以上基本上是正確的做法。您只需要添加繁瑣的'malloc'和'strncpy'來創建一個完整的副本。答案是:上面的,加上C. –