NSString到const void *

时间:2018-06-05 08:42:37

标签: objective-c

如何将NSString转换为const void?

我试过

NSString *testString = @"testString";
const void *testConstVoid = CFBridgingRetain(testString);

但是testConstVoid仍然是一个nsstring

2 个答案:

答案 0 :(得分:1)

而不是CFBridgingRetain(testString),您应该使用testString.UTF8String

NSString *testString = @"testString";
const void *testConstVoid = testString.UTF8String;

结果

enter image description here

答案 1 :(得分:0)

除了UTF8String之外,您还有cStringUsingEncoding:getCString:maxLength:encoding:

在前两种情况下,如果您计划在原始NSData生命周期之后使用它,则需要将返回的C字符串复制到您自己的字符缓冲区或NSString

NSString *str = @"hello";
const char *cStr = str.UTF8String;
const NSUInteger cStrLen = [str lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSMutableData *cStrData = [[NSMutableData alloc] initWithBytes:cStr
                                                        length:cStrLen + 1];
    // +1 for '\0' (C string null-terminator)
const void *cStrBytes = cStrData.bytes;