开发者

Simple question on releasing allocated memory

开发者 https://www.devze.com 2023-01-09 14:15 出处:网络
i开发者_StackOverflown several example codes one can find this static NSNumberFormatter *numberFormatter = nil;

i开发者_StackOverflown several example codes one can find this

static NSNumberFormatter *numberFormatter = nil;
if (numberFormatter == nil) {
    numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    [numberFormatter setMaximumFractionDigits:6];
}

Isn't that code producing memory leaks? Or is there some inbuilt magic, which frees the alloc'ed memory?

Regards


It seems to me that this piece of code comes from somewhere that implemets the "singleton pattern", or something very similar to it. Since the variable is static, its value will be remembered between function calls. This means that it is allocated only once in the life of the application.

In this code, the numberFormatter variable seems to be something that can be needed by the application at anytime during its entire lifetime - threfore is not necessary to free it.
More correctly, it may be impractical to free it if it is frequently needed by the application. That would cause unnecessary memory allocation and deallocation operations.

Note that all memory which belongs to your application gets freed by the operating system after the application is no longer running.
This way, the memory allocated to that variable will be freed, too.

If this object used resources other than the memory, it would need explicit cleanup, but if not, this is not required.


I don't think it will leak memory, because the numberFormatter variable is static, meaning there's only one copy of it and the reference stays around between function calls. Since the only time you're making a new one is if one doesn't exist yet, you'll only ever have one copy.


It would appear that the intent of this code is to allocate numberFormatter once and keep it alive throughout the life of the program. Since all memory is freed automatically when an application is closed, it is not necessary free the memory when used in this way. Nevertheless, it is still good practice to release every piece of memory you retain.


This example will be leaking. You have a retain count of one here...

numberFormatter = [[NSNumberFormatter alloc] init];


When you do an "alloc", like this:

numberFormatter = [[NSNumberFormatter alloc] init];

you have to "release" the object, or it will leak:

[numberFormatter release];
0

精彩评论

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