views:

1063

answers:

2

Hi,

Im pretty new to objective-c programming and releasing of objects is my greatest headache. I'm always doubting on what need to be released, and my times I've end up releasing the wrong variable and getting a BAD EXEC crash. I've read apple's guide on memory management, but I cant always go from their examples to my code.

One of these situations is my singletons (Im a big Singleton guy).

I have one define as this:

static Configuration* _instance;

+(Configuration*)getInstance{
    if (_instance == NULL){
     _instance = [Configuration alloc];
     [_instance initConfig];
    }
    return _instance;
}

In my code I use it like this:

//Store configuration  
Configuration* conf = [Configuration getInstance]; 
conf.userName = self.userName.text;
conf.cellPhone = self.phoneNumber.text;

Do I need to release the "conf" variable?

When should I release the _instance?

Since Im running this code on iPhone, what happens with the vars I don't release? will they affect the iPhone performance?

Thanks in advance! Gonso

+3  A: 

You don't need to release your conf variable since you haven't retained it.

As a rule of thumb, you need to balance the calls to methods that increment a retain count with methods that decrement it.

init, retain, increment it, while release decrements it.

The main _instance is released when the class is unloaded, so I think you don't need to care about it.

pgb
+3  A: 

When you created the Configuration instance with "_instance = [Configuration alloc]; [_instance initConfig];" it had a retain count of one from the alloc call. If you were to release conf after "conf.cellPhone = self.phoneNumber.text;" then it would be deallocated at that point.

When you first create an object with alloc, or copy, or mutableCopy it will have a retain count of 1. Each call to retain increases that retain count by one. Each call to release decreases that retain count by 1. Calling autorelease just means "Call release for me later", so if retains and releases are like checks, autorelease is like future dating a check.

Your code that accesses the Configuration singleton does not retain it, copy it, or mutable copy it, so it should not release it.

As your code is written now, the Configuration object will never be released, and will live for then entirety of the applications life, which is typically what you want with a singleton.

Jon Hess