neil
neil

Reputation: 111

Simple question on releasing allocated memory

in 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

Upvotes: 2

Views: 281

Answers (5)

Venemo
Venemo

Reputation: 19097

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.

Upvotes: 4

pimpampoum
pimpampoum

Reputation: 5994

When you do an "alloc", like this:

numberFormatter = [[NSNumberFormatter alloc] init];

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

[numberFormatter release];

Upvotes: -1

5ound
5ound

Reputation: 1199

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.

Upvotes: 1

Sophie Alpert
Sophie Alpert

Reputation: 143194

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.

Upvotes: 2

Lee Armstrong
Lee Armstrong

Reputation: 11450

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

numberFormatter = [[NSNumberFormatter alloc] init];

Upvotes: 0

Related Questions