为什么要保留静态变量?
是否没有必要保留静态变量,因为它在程序运行期间一直存在,无论您是否释放它?
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我假设您指的是静态对象指针,例如 static NSString *foobar; 。
这些变量的生命周期确实与应用程序一样长,但我们讨论的变量只是指针。在 Objective-C 中,对象总是动态分配的,因此我们总是使用指向其类型的指针来寻址它们,但对象的基础数据仍然存在于那边动态分配的野蓝色中。
您仍然必须保留该对象,因为虽然指向该对象的指针永远不会超出范围,但该对象本身可以像任何其他对象一样被释放,因此您的指针最终将指向垃圾,或更糟糕的是,另一个不相关的对象。
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 接受的答案的简化版本:
retain
不适用于指向对象的变量。该变量将永远存在,因为它是静态的。retain
用于变量指向的对象。如果没有retain
,对象可以(并且应该)被释放。然后你就有一个变量指向一个会导致sigabrt
的事物。这个无处指向的变量被称为“悬空指针”。对于 ARC 上下文,最好的办法是将静态变量声明为强变量,如下所示:
这确保了
thatStaticVariable
指向的对象将是一个有效的对象(即永远不会被释放) )一旦分配。 但是,您实际上根本不需要 __strong 关键字,因为它是默认关键字(所以说 文档,感谢@zpasternack),所以只要使用就可以了。
注意:永远=应用程序运行时
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. Theretain
is for the object the variable points to. Without theretain
the object could (and should) be deallocated. Then you've got a variable pointing to a thing which will cause asigabrt
. 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:
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 useand you're good.
Note: forever = while the application is running