开发者

Constant Array and Memory Management

开发者 https://www.devze.com 2023-01-09 00:05 出处:网络
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,};

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消