Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

objective-C: simple question about copy/retain NSString

If I set a NSString as property

@property (copy) NSString* name;

I always want to use (copy), so that if its value change, all object with such string still have the old value (as specifiedhere).

However, what happens if my NSString is not a class property, but it is just declared in the code ? Is in that case retained or copied everytime I assign a new value ?

thanks

like image 350
aneuryzm Avatar asked Dec 06 '22 21:12

aneuryzm


2 Answers

It depends on how you declare it. You should read the documentation on memory management. Basically the rules are:

NSString *aString = [NSString stringWithString:@"Hello"];
NSString *bString = [NSString stringWithFormat:@"%@", @"Hello"];

In these cases, the string is not copied or retained. It is autoreleased, which means it will be automatically deallocated the next time the autorelease pool drains. You do not have to call the release method on them. (So assigning a new value will not cause it to leak.)

NSString *cString = [[NSString alloc] initWithFormat:@"%@", @"Hello"];
[cString release];

According to Objective C convention, methods that use alloc and have a retain count of one are not autoreleased, so you need to release them explicitly. Assigning a new value without releasing the old one will cause a leak.

You can also explicitly call a "copy" method or a "retain" method on a string. In either case, the new string will have a retain count of 1 and will not be autoreleased, so you will need to call the release method on it before you assign a new value.

NSString *dString = [cString retain];
NSString *eString = [cString copy];

...
[dString release];
[eString release];

If it is a property, and you use self.variableName, this will be taken care of for you (through the getters and setters which are generated with @synthesize). If you do it explicitly, you must make sure to call release on variables that you have called retain or copy on.

Edit: As some commentators below have noted, thinking about management in terms of "ownership" is usually the preferred of describing these ideas, rather than retain count.

like image 194
Matthew Gillingham Avatar answered Dec 31 '22 06:12

Matthew Gillingham


If it's not a property and just declared in code, you need to explicitly retain or copy it, ie

NSString myString = [otherString copy];

or

NSString myString = [otherString retain];

Either way you also need to ensure it's released at somepoint.

like image 26
Tom Jefferys Avatar answered Dec 31 '22 06:12

Tom Jefferys