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];
Filters. (computing) Automatic release (of previously allocated resources)
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.
-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.
Realloc() If you need to reallocate a memory block, you can use the realloc() function… void* realloc (void* ptr, size_t size);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With