I have a global NSString variable declared in a .m file. When I use the stringWithFormat to give it a string value anywhere within the .m file, that value does not persist in between function calls. However when I do the same using stringWithString, the value persists throughout the implementation and any functions calls thus giving it a true global behavior. Rather to put it differently, how does the memory management differ internally for stringWithFormat vs stringWithString?
Why does the value persist for stringWithString while throwing a "message sent to deallocated instance" (on subsequent use of the NSString say in a NSLog statement in another function which comes after a function that gave the NSString a value using stringWithFormat) when using stringWithFormat? No such issues when I replace the same with stringWithString.
Thanks!
EDIT: I forgot to mention that YES it worked in case of stringWithFormat when I did a manual retain afterward. The value persisted. Hence the question.
the compiler is smart, and instead of creating dozens of different NSString instances that all hold the same value he creates one instance that can't be released and all the other instances just point to the NSString that is hardcoded in your program.
And because the hardcoded NSString gets never deallocated you can use it even after the autorelease pool would have deallocated it.
This just covers your wrong memory management. And you should definitely not rely on this behaviour.
Edit. there is not much more to say. The NSString that you've created with stringWithString:literal will simply point to the location of literal in memory.
A little example:
you will see they all point to the same address.
And all of them will never get deallocated. So you could access string5 from some other method in your code and it would still point to the address 295740, and the NSString "Foo" would still be there.
But a NSString object that does not point to a string literal would be deallocated at this time, and you would get a bad access exception.
You are violating the memory management rules but you will never notice it if you only use string literals. Until the behaviour of the compiler changes.
So do it right, learn proper memory management and don't rely on internals. Retain all your autoreleased objects if you need them later. Even if they point to string literals