1

I'm a bit confused as to whether NSStrings should ever be retained and synthesized. I have a NSString value as an instance variable, and am retaining and synthesizing it. But I am assigning it different values such as:

self.value = @"VALUE";
....
self.value = @"DIFFERENT_VALUE";

I'm not actually calling alloc anytime. Do I need to retain and synthesize this variable then?

Dair
  • 15,910
  • 9
  • 62
  • 107
Henley
  • 21,258
  • 32
  • 119
  • 207

3 Answers3

3

You can think of on-the-fly strings as autoreleased in terms of how you use them, although in reality they will probably stay around as fixed values... because you are using the accessors they will automatically get copied or retained (however you marked the accessor) and so you do need to release them in dealloc.

As for the need to @synthesize, remember all that is doing for you is actually creating the get/set methods that take the variable and place it in your iVar. So not matter what you either need to @synethsize a property OR create the get/methods yourself - usually far better just to use @sythesize.

Kendall Helmstetter Gelner
  • 74,769
  • 26
  • 128
  • 150
1

You should as you'll never know how you are going to change the use of the code in the future. Change the code to use dynamically created strings, and it will break if don't follow the rules.

Also note that the best practice for NSString is to set it to copy instead of retain. The reason is simple, this prevents the string from being changed under your feet.

See NSString property: copy or retain? for more details.

Community
  • 1
  • 1
jonny
  • 111
  • 2
  • 6
0

If you have never alloc'ed them, you usually don't need to retain, but if they are instance variables in your objects, they are probably marked as retain or copy so at your object's dealloc method you should release these objects if there is a value on it.

Maurício Linhares
  • 39,901
  • 14
  • 121
  • 158