Constant Array and Memory Management
I have defined a constant array in one of my classes as:
st开发者_如何转开发atic 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?
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:
const float *make_values() {
float *v = (float *)malloc(6*sizeof(float));
v[0] = -0.5f;
v[1] = -0.33f;
...
return v;
}
const float *values = make_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.
精彩评论