views:

67

answers:

5

Hi,

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

A: 

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

numberFormatter = [[NSNumberFormatter alloc] init];
Lee Armstrong
+4  A: 

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.

Venemo
+2  A: 

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.

Ben Alpert
A: 

When you do an "alloc", like this:

numberFormatter = [[NSNumberFormatter alloc] init];

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

[numberFormatter release];
micropsari
You forgot that the variable is static in this example.
Venemo
+1  A: 

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.

5ound