views:

47

answers:

2

When converting a NSString to a char* using UTF8String, how to retain it?

According to the following link, when you use UTF8String the returned char* is pretty much autoreleased, so it won't last beyond the current function: http://developer.apple.com/mac/library/documentation/cocoa/reference/Foundation/Classes/NSString_Class/Reference/NSString.html#jumpTo_128

It says i have to copy it or something to keep it around. How can i do this?

The reason i ask is that if i do [myCharPointer retain] it doesn't retain it because it's not an obj-c object, it's a c pointer.

Thanks

A: 

Try using -getCString:maxLength:encoding:, e.g.:

NSUInteger bufferCount = sizeof(char) * ([string length] + 1);
const char *utf8Buffer = malloc(bufferCount);
if ([string getCString:utf8Buffer 
             maxLength:bufferCount 
              encoding:NSUTF8StringEncoding]) {
    NSLog("Success! %s", utf8Buffer);
    free(utf8Buffer); // Remember to do this, or you will get a memory leak!
}
meeselet
Wouldn't i need to malloc +1 byte for the null terminator?
Chris
Right :-). I've edited it to take that into account.
meeselet
+2  A: 

You can use strdup()

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

When you are done with stringIWantToKeep, you free it as though it was originally malloc'd.

JeremyP