by now i was always did the same :
NSString *ran = @"check";
now when i wanted to copy an nsstring1 to nsstring2 , i have been told here that i have to copy/retain the nsstring instance, in a various methods(with property retain/copy) ..
NSString *animation = [ran copy];
i know and understand how to do that , but cant understand why .
what exactly happen with the memory here? i just couldnt understand what happen when i do the copy/retain thing , and when should i do that ? (in the above first exampe also?? )
all explanations here are about the difference between copy/retain , but i couldnt found anything about the REASON , i have to copy a class instance .
You would copy a string if you need it to be immutable, and you don’t know if it is immutable. Say you have this method:
You expect me to call your method like this:
But I might instead do this:
and then a while later I might do this:
Since your
setName:method only retained the string it was passed, I have changed the value of your private_namevariable without you knowing about it. Maybe you were depending on it not changing.To prevent such sneakiness, you can write your
setName:method like this:Now you create an immutable copy of whatever name I pass in. If I pass in a mutable string, and then change it, your
_namewon’t be affected.