常量数组和内存管理
我在我的一个类中定义了一个常量数组:
static const float values[] = {-0.5f, -0.33f, 0.5f, -0.33f, -0.5f, 0.33f,};
在我的类的dealloc方法中,我需要释放该字段占用的内存吗?我该怎么做?我应该使用 NSArray 来代替吗?
I have defined a constant array in one of my classes as:
static const float values[] = {-0.5f, -0.33f, 0.5f, -0.33f, -0.5f, 0.33f,};
In the dealloc method of my class, do I need to free the memory occupied by this field? How do I do it? Should I use NSArrays instead?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,您永远不需要释放静态分配的数组。它在进程启动时由系统分配,并保留在范围内直到退出。
就此而言,对于非静态数组也不需要它,因为它包含在类中,因此与类一起生死。
唯一需要担心生命周期的时候是在堆上分配数组时,这对于
const
值数组来说有点棘手:只有这样,您才需要担心释放内存,然后您可能需要考虑使用带有保留语义的 NSArray 属性。
No, you never need to free a statically allocated array. It is allocated by the system when the process starts and remains in scope until it exits.
For that matter, you don't need it for a non-static array either, since it is contained within the class, and so lives and dies with the class.
The only time you need to worry about lifetimes is when you allocate the array on the heap, which is a bit tricky to do for an array of
const
values:Only then you would have to worry about releasing the memory at some point, and then you might want to consider using an NSArray property with retain semantics.