Objective-C: a simple question about copying / saving NSString

If I set the NSString property as a property

@property (copy) NSString* name; 

I always want to use (copy), so if its value changes, all objects with such a string still have the old value (as indicated here ).

However, what happens if my NSString is not a property of the class, but it is just declared in code? In this case, is it saved or copied every time I assign a new value?

thanks

+4
source share
3 answers

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

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

In these cases, the string is not copied or saved. It is auto-implemented, which means it will be automatically released the next time the auto-ad pool is depleted. You do not need to call the release method on them. (Therefore, assigning a new value will not leak it.)

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

According to the Objective-C convention, methods that use alloc and have an account to save one are not auto-implemented, so you need to explicitly free them. Assigning a new value without releasing the old will result in a leak.

You can also explicitly call the copy method or the save method on a string. In any case, the new line will have a storage counter of 1 and will not be auto-implemented, so you will need to call the release method on it before assigning a new value.

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

If this property is, and you use self.variableName, it will take care of you (through the getters and setters that are generated using @synthesize). If you do this explicitly, you should definitely call release on the variables that you called saved or copied.

Edit: As some commentators have noted below, thinking about management in terms of “ownership” is usually preferable to describe these ideas rather than keep an account.

+9
source

If this is not a property and just declared in the code, you need to explicitly save or copy it, i.e.

 NSString myString = [otherString copy]; 

or

 NSString myString = [otherString retain]; 

In any case, you also need to ensure his release at some point.

+4
source

If you do not use a property setting tool, for example self.name = @"foo" or [self setName:@"foo"] , but rather assign a variable directly, for example name = @"foo" , it does not matter how the property is declared.

You should understand that property syntax is just a shortcut to writing access methods ( -name and -setName: in this case). If you don't call these methods (implicitly by setting the property), it doesn't matter how they work internally (this is what you specify with retain or copy ).

+2
source

All Articles