使用UTF8String将NSString转换为char*时,如何保留它?

Chr*_*ris 2 iphone memory-management objective-c

使用UTF8String将NSString转换为char*时,如何保留它?

根据以下链接,当您使用UTF8String时,返回的char*几乎是自动释放的,因此它不会超出当前函数:http: //developer.apple.com/mac/library/documentation/cocoa/reference/基金会/班/ NSString_Class /参考/ NSString.html#jumpTo_128

它说我必须复制它或其他东西来保持它.我怎样才能做到这一点?

我问的原因是,如果我[myCharPointer retain]它不保留它,因为它不是obj-c对象,它是ac指针.

谢谢

Jer*_*myP 6

您可以使用 strdup()

const char* utf8Str = [@"an example string" UTF8String];
if (utf8Str != NULL) 
{
    stringIWantToKeep = strdup(utf8Str);
}
Run Code Online (Sandbox Code Playgroud)

当你完成后stringIWantToKeep,你释放它就像它最初是malloc'd一样.