为什么要保留静态变量? [英] Why retain a static variable?

查看:107
本文介绍了为什么要保留静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不是一个静态变量,因为它在程序运行期间一直存在,无论您是否释放它,都没有必要吗?

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?

请参阅以下代码: https://github.com/magicalpanda/MagicalRecord/blob/master/Source/Categories/NSManagedObjectContext + MagicalRecord.m#L24-29

推荐答案

我假设您是指静态对象指针,例如static NSString *foobar;.

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

此类变量确实具有与应用程序一样长的生命周期,但是我们正在讨论的变量仅是指针.在Objective-C中,对象始终是动态分配的,因此我们总是使用指向其类型的指针对其进行寻址,但是对象的基础数据仍然存在于动态分配的野生蓝色峡谷中.

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.

您仍然必须保留该对象,因为指向该对象的 pointer 永远不会超出范围,而该对象本身可以像其他任何对象一样被释放,因此您的指针将最终结束指向垃圾,或更糟糕的是,另一个不相关的对象.

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.

这篇关于为什么要保留静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆