Curnelious
Curnelious

Reputation: 1

Why copy an NSString instead of just retaining it?

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 .

Upvotes: 1

Views: 146

Answers (1)

rob mayoff
rob mayoff

Reputation: 385500

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:

- (void)setName:(NSString *)newName
{
    _name = [newName retain];
}

You expect me to call your method like this:

[yourObject setName:@"Rob"];

But I might instead do this:

NSMutableString *sneaky = [NSMutableString stringWithString:@"Rob"];
[yourObject setName:sneaky];

and then a while later I might do this:

[sneaky appendString:@"ert"];
// sneaky is now @"Robert"

Since your setName: method only retained the string it was passed, I have changed the value of your private _name variable 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:

- (void)setName:(NSString *)newName
{
    _name = [newName copy];
}

Now you create an immutable copy of whatever name I pass in. If I pass in a mutable string, and then change it, your _name won't be affected.

Upvotes: 5

Related Questions