问题
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
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/6316723/why-retain-a-static-variable