How is the memory of returned C types handled under GC?
According to the documentation for NSString's method -UTF8String
:
The returned C string is automatically freed just as a returned object would be released; you should copy the C string if it needs to store it outside of the autorelease context in which the C string is created.
So under retain/release memory 开发者_如何学Gomanagement, the following method:
- (const char*) giveMeACString
{
NSString* string = @"I'm a string!";
return [string UTF8String];
}
is fine, so long as the calling method treats the returned const char* as it would an autoreleased object.
However, under garbage collection there isn't an autorelease context, as far as I'm aware. And C types aren't garbage collected, so it doesn't look like the GC will treat the returned pointer as it would a returned object.
What is its lifespan tied to? Is it still freed at a point in the thread's runloop that is reliably `later on', or does it behave differently under GC than under non-GC?
I think the memory is allocated from garbage collected memory and the return type is __strong const char*
. This means that it will be collected in the normal way when it is not reachable from the root set of pointers.
That basically means you need to store it in a pointer variable that is marked as __strong
or it will be collected at some point.
I'd speculate that an immutable string maintains a reference to the UTF8 version of itself, so it only has to calculate it once and therefore the UTF8 string probably won't go away until the NSString does which is why you don't have to worry about it disappearing normally.
Since you did not explicitly allocate those spaces, you do not need to worry about deallocation.
精彩评论