Why retain a static variable?

ぃ、小莉子 提交于 2019-11-28 06:27:59

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.

Dan Rosenstark

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!