Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autorelease vs. Release

Given the two scenarios, which code is best practice and why?

Autorelease

loginButton = [[[UIBarButtonItem alloc] initWithTitle:@"Login" 
                                                style:UIBarButtonItemStylePlain 
                                                target:self 
                                                action:@selector(loginButtonClicked:)]
                                                autorelease];
self.navigationItem.rightBarButtonItem = loginButton;

or

Release

loginButton = [[UIBarButtonItem alloc] initWithTitle:@"Login" 
                                                style:UIBarButtonItemStylePlain 
                                                target:self 
                                                action:@selector(loginButtonClicked:)];
self.navigationItem.rightBarButtonItem = loginButton;
[loginButton release];
like image 695
Sheehan Alam Avatar asked May 05 '10 20:05

Sheehan Alam


People also ask

What does Autorelease mean?

Filters. (computing) Automatic release (of previously allocated resources)

What is Autorelease Objective C?

An autorelease pool is actually a collection of objects that will be released at some point in the future (either at the end of the thread's run loop or at the end of the scope of an autorelease pool). When a pool is drained, all the objects in the pool at that time are sent the release message.

What is Dealloc in C?

-dealloc is an Objective-C selector that is sent by the Objective-C runtime to an object when the object is no longer owned by any part of the application. -release is the selector you send to an object to indicate that you are relinquishing ownership of that object.

Which of the following do you use to deallocate memory free () Dalloc () Dealloc () Release ()?

Realloc() If you need to reallocate a memory block, you can use the realloc() function… void* realloc (void* ptr, size_t size);


2 Answers

For your example, it doesn't really matter. Personally, I would probably use the first case. That would let you add modifications or debugging code later without having to worry about moving the [loginButton release] line around.

like image 68
Carl Norum Avatar answered Sep 21 '22 08:09

Carl Norum


There seems to be a stigma against using autorelease (i.e. prefer to release whenever possible), which is why I typically go the second route. But since you're not in a loop here, releasing now vs. autoreleasing later will have exactly the same effect (since another object has retained loginButton, it won't be dealloc()ed).

But I should point out that most of my memory leaks are caused by forgetting to add the release line, so it would probably be better to just tack on the autorelease right away.

like image 27
Brian Avatar answered Sep 24 '22 08:09

Brian