The docs vaguely say that it will stick around as long as needed, but when is it actually deallocated? When the original NSString is deallocated? When the current autorelease pool clears? Sometime else? Furthermore, when is it guaranteed to stay for, as opposed to the current implementation? If it stays for the lifetime of the NSString, will the same pointer be returned every time?
Thanks
Update 30/11/2018
As David Dunham pointed out in comments, the Apple documentation has changed (the old link in my answer is now broken).
The Apple documentation now says:
My original answer is now wrong in two parts.
My claim that the UTF8 string could possibly survive the deallocation of the
NSStringis explicitly denied by the current Apple documentation.In the Apple docs “Autorelease context” has been replaced by “memory context”. I’m not sure what that means exactly, but you probably should not trust the pointer after you have exited the scope in which it was acquired.
The Original Answer
The Apple documentation (broken link) says:
That seems pretty non vague to me.
NB You shouldn’t really worry about what the current implementation does. Implementations change
Extrapolating the above, the answers to your questions are probably:
When the autorelease pool is drained.
No. The documentation implies you could alloc a string, take the UTF8String then release the string and the UTF8String would still be valid but be aware of this line from the Memory Management Rules:
“Modifying an object” might include releasing the NSString you got the UTF8 string from.
That’s what the docs say.
No.
If it’s not documented, it’s not guaranteed.
I doubt it. Maybe for immutable strings, the UTF8 string is cached, but maybe not. Why not write some code to try it out? In any case, you can’t rely on it in production code, nor in any situation where your NSString might really be an NSMutableString.