15

The StackOverflow question "using static keyword in objective-c when defining a cached variable" references code from Example 4 of Xcode's TableViewSuite that defines a static NSDateFormatter and calls alloc but never calls release.

Shouldn't static variables be released? If yes, where in the code should they be released? If no, why not?

Community
  • 1
  • 1
ma11hew28
  • 121,420
  • 116
  • 450
  • 651

2 Answers2

16

Shouldn't static variables be released? If yes, where in the code should they be released? If no, why not?

It depends. If the variable is initialized only once, and should stay around for the lifetime of the application, then no, it shouldn't be released (its memory will essentially be freed when the application exits, anyway). If, however, the value of the static variable changes, then yes, the previous object should be released when the static variable is set to a new object.

mipadi
  • 398,885
  • 90
  • 523
  • 479
2

As the accepted answer to that question already states, releasing static variables is impossible. They act like global variables that are only visible to your function with a lifetime as long as your program.

If you are concerned about bloat because of variables that that static variable holds on to, then you should (somehow) release those references. Thus, for example, if your static variable is an NSMutableArray, and you keep adding objects inside, it will always keep growing, unless you, at some point, empty the array.

Community
  • 1
  • 1
paracycle
  • 7,665
  • 1
  • 30
  • 34
  • 5
    It’s perfectly possible to release static variables. – zoul Apr 06 '11 at 15:25
  • 1
    @zoul: It may also be worth pointing out that setting it to `nil` after releasing is a good idea, or else (in the linked code example) you will end up overreleasing. – jscs Apr 06 '11 at 18:00
  • @zoul: I meant to say that it is impossible to get rid of the **static variable**, the lifetime of that variable is for the length of the application (as opposed to any local variables or ivars). It is perfectly possible to release the **value** that the static variable holds. – paracycle Apr 06 '11 at 18:39