开发者

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

开发者 https://www.devze.com 2023-01-06 01:38 出处:网络
When converting a NSString to a char* using UTF8String, how to retain it? According to the following link, when you useUTF8String the re开发者_JS百科turned char* is pretty much autoreleased, so it wo

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

According to the following link, when you use UTF8String the re开发者_JS百科turned 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


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.


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!
}


If you need an object to retain/release as every other object you can do the following:

NSData* storage= [yourNSString dataUsingEncoding:NSUTF8StringEncoding];
char* yourCString= (char*)storage.bytes;
// your code flow here

Now you can pass both storage and yourCString to any function retaining/releasing storage as you like, when the retain count of storage will go to 0 the memory pointed by yourCString will be freed too.

I used this to keep a single copy of a very long string while having references created by strtok_r in beans and have the memory released only when all beans had been released.

A little note about (missing) BOM:

As stated here http://boredzo.org/blog/archives/2012-06-03/characters-in-nsstring dataUsingEncoding: should add BOM but i've checked with the debugger and there is no BOM in the returned bytes.

0

精彩评论

暂无评论...
验证码 换一张
取 消