Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why retain a static variable?

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

like image 818
ma11hew28 Avatar asked Jun 11 '11 15:06

ma11hew28


2 Answers

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.

like image 187
Jonathan Grynspan Avatar answered Jan 17 '23 16:01

Jonathan Grynspan


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

like image 45
Dan Rosenstark Avatar answered Jan 17 '23 17:01

Dan Rosenstark