简单的答案与证据。NSString stringWithCString:encoding: 复制字节缓冲区来生成字符串。缓冲区由您来维护。
证明:
代码:
const char* hardString = "Hello, World";
char *buffer = nil;
buffer = calloc(13, 1);
bzero(buffer, 13);
memcpy(buffer, hardString, 12);
NSString *aString = [NSString stringWithCString:buffer encoding:NSUTF8StringEncoding];
NSLog(@"aString: %@ \t filled buffer:(%p) [%s]", aString, (void*)buffer, buffer);
bzero(buffer, 13);
NSLog(@"aString: %@ \t zeroed buffer:(%p) [%s]", aString, (void*)buffer, buffer);
free(buffer);
NSLog(@"aString: %@ \t free'd buffer:(%p)", aString, (void*)buffer);
buffer = nil;
NSLog(@"aString: %@ \t nulled buffer:(%p)", aString, (void*)buffer);
结果:
aString: Hello, World filled buffer:(0x10010a790) [Hello, World]
aString: Hello, World zeroed buffer:(0x10010a790) []
aString: Hello, World free'd buffer:(0x10010a790)
aString: Hello, World nulled buffer:(0x0)