views:

138

answers:

2

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

A: 

Typically this occurs when the NSAutoreleasePool receives the -drain message, assuming there are no lingering references.

Edit: Link to 'the rules'

jer
That is also incredibly vague, for instance, lingering references to what? On the iPhone there is no CG, so are you talking about retains to the NSString?
Jared P
I assume some familiarity with the rules. Editted the post to link with them.
jer
A: 

The Apple documentation says:

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.

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:

but when is it actually deallocated?

When the autorelease pool is drained.

When the original NSString is deallocated?

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:

A received object is normally guaranteed to remain valid within the method it was received ... although you must also take care if you modify an object from which you received another object.

"Modifying an object" might include releasing the NSString you got the UTF8 string from.

When the current autorelease pool clears?

That's what the docs say.

Sometime else?

No.

Furthermore, when is it guaranteed to stay for, as opposed to the current implementation?

If it's not documented, it's not guaranteed.

If it stays for the lifetime of the NSString, will the same pointer be returned every time?

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.

JeremyP