iPhone/iPad/iPod touch 上全局变量和类变量的内存问题
什么时候应该使用全局变量,什么时候应该使用类变量,为什么?
希望您的经验和想法能够与我们这个平台的新手分享。
示例:
让我需要跟踪图层上触摸事件的时间戳和位置(例如触摸开始、结束)。我可以使用实现触摸事件的类的全局变量或类变量来跟踪它。我应该怎么办?
问候,
-萨达特
When we should use global variable and when class variable and why?
I hope your experiences and ideas to share with us who are novice in this platform.
Example:
Let, i need to trace timestamp and position of touch events (eg. touch start, end) on a layer. I can trace it using global variable or class variable of the class which implements touch event. What should I do?
Regards,
-Sadat
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是 Objective C 或 iPad 系列设备特有的问题。
变量应该具有所需的最小“可见性”和“持续时间”,仅此而已。
您必须想出一些非常令人信服的理由来尝试通过我们的代码审查流程获取全局变量。它们几乎总是能够被更合适的东西所取代。
回复您的评论:
此处有一个很好的片段,详细说明了如何处理类级别变量。这些是普通的 C 文件范围变量,因此它们在文件外部不可见,但您只能为类获得一个变量,而不是为您实例化的每个对象获得一个变量。
从这个意义上说,它们具有全局的优点(最小的存储空间并且该值仍然可以读取),而没有缺点(污染全局名称空间并使类外部的代码可以更改它)。
并且,如果不需要在文件外部读取它,则无需提供
initCount
方法。This isn't a problem specific to Objective C or the iPad family of devices.
Variables should have the minimum "visibility" and "duration" that they need, and no more.
You would have to come up with some very convincing reasons for trying to get a global variable through our code review processes. They're almost always able to be replaced with something a little more appropriate.
In response to your comment:
There's a nice snippet over here which details how to do class level variables. These are normal C file-scoped variables so they're not visible outside the file but you only get one for the class, not one for every object that you instantiate.
In that sense, they have the advantages of a global (minimal storage and the value is still accessible for reading) without the disadvantages (polluting the global name-space and making it possible for code outside of the class to change it).
And, if it doesn't need to be read outside of the file, just don't provide the
initCount
method.这是一个翻转的答案,但根本不使用全局变量 - 坚持使用类方法和预期的封装。任何其他事情,你都会从黄昏到黎明与可可库战斗。如果您遵循他们的模式,包括类方法、封装、委托等,那么您将花费相对较少的努力取得巨大的进展。
在我的努力中,我可能认为将某些内容称为“全局变量”的唯一地方是项目范围的常量 - 所以根本不是变量,但有时整个项目非常需要一个常量(我想到了 TableViewCell 标识符)
It's kind of a flip answer, but don't use global variables at all - stick with class methods and expected encapsulation. Anything else and you'll be fighting the cocoa libraries from dusk to dawn. If you follow their patterns, which include class methods, encapsulation, delegation, etc - you'll be making huge headway with relatively little effort.
The only place where I might think to call something a "global variable" in my efforts are project-wide constants - so not variables at all, but sometimes there's a good need for a constant across your project (TableViewCell identifiers comes to mind)