Domanda

In which circumstances I should use the autoreleased variables? And which approach is best from the following ..

  1. Use obj= [[_className alloc]init]autorelease],

  2. obj = [[_className alloc]init] And release the obj as[obj release]

    Please help.

Also what should I use when I want alocal object to be created and used in loop control structure such as follows . .

for(int i = 0;i<10;i++)
{
    _className obj = [[_className alloc]init];//Should I use autorelease here?
                                              
       .
       . // Use this obj.. 
       .
    [obj release];//If autoreleased is not used...
}

What should I use here from listed options? Which should be better and optimized?

È stato utile?

Soluzione

The best approach is to use ARC and not have to worry about it.

But if you are not using ARC I usually liked case 2 better most of the time. The question is when is the current autorelease pool going to be drained. If there is a loop with a lot of work or I am in a library not knowing the context it will run in I can control when the object is released instead of autoreleasing and it happening at some unknown time in the future. I could make my own autorelease pool for the loop but I preferred the explicit release.

A place I see case 1 used is when assigning an object to a property so it would be a one line statement using autorelease instead of allocate, assign to property, release.

Is there a reason you would not use ARC?

Altri suggerimenti

If you are not using ARC then shortly i would say use autorelease when you don't know the scope of your variable. And use release when you know the scope of your variable.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top