19

Isn't it unnecessary to retain a static variable since it stays around for the duration of the program, no matter if you release it?

See this code: https://github.com/magicalpanda/MagicalRecord/blob/master/Source/Categories/NSManagedObjectContext+MagicalRecord.m#L24-29

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
ma11hew28
  • 121,420
  • 116
  • 450
  • 651

2 Answers2

39

I'm assuming you mean a static object pointer, such as static NSString *foobar;.

Such variables indeed have a lifetime as long as the application, but the variables we're talking about are pointers only. In Objective-C, objects are always dynamically allocated, and so we always address them with a pointer to their type, but the underlying data for an object is still present out in the dynamically allocated wild blue yonder.

You must still retain the object because, while the pointer to the object will never go out of scope, the object itself can be deallocated just like any other object, and so your pointer will end up pointing to garbage, or worse, another unrelated object.

Jonathan Grynspan
  • 43,286
  • 8
  • 74
  • 104
  • 4
    Jonathan is right! What if the argument passed is in an autorelease pool and will be autoreleased just after the method is called?! -> accessing the static pointer will cause a failure (EXEC_BAD_ACCESS mostly) – Martin Ullrich Jun 11 '11 at 15:31
  • Martin, a small correction: that's EXC_BAD_ACCESS (EXC as in exception). – bneely Feb 12 '12 at 02:24
18

A simplified version of Jonathan Grynspan's accepted answer:

The retain isn't for the variable which points to an object. That variable will last forever because it's static. The retain is for the object the variable points to. Without the retain the object could (and should) be deallocated. Then you've got a variable pointing to a thing which will cause a sigabrt. This variable pointing nowhere is known as a "dangling pointer."

For the ARC context, the best thing to do is declare the static variable as strong, so something like this:

static ThatClass * __strong thatStaticVariable;

This ensures that the object that thatStaticVariable points to will be a valid object (i.e., never gets deallocated) once assigned. However, you don't actually need the __strong keyword at all, because it's the default (so sayeth the docs, thanks to @zpasternack), so just use

static ThatClass *thatStaticVariable;

and you're good.

Note: forever = while the application is running

GraniteRobert
  • 190
  • 1
  • 10
Dan Rosenstark
  • 68,471
  • 58
  • 283
  • 421
  • 5
    Under ARC, any retainable object without an explicit ownership qualifier is implicitly __strong, so sayeth [the docs](http://clang.llvm.org/docs/AutomaticReferenceCounting.html#ownership.inference). – zpasternack Feb 12 '12 at 03:09