Reputation: 49077
If I have a property like this:
@property (nonatomic, retain) UILabel* lblUsername;
Should I in viewDidLoad
do this:
self.lblUsername = [[[UILabel alloc] init...] autorelease];
self.lblUsername.text = @"A label";
self.lblUsername....
Or should I do this:
UILabel* usernameLabel = [[UILabel alloc] init...];
usernameLabel.text = @"A label";
usernameLabel....
self.lblUsername = usernameLabel;
[usernameLabel release];
I have seen both and I am unsure which I should use, any benefits of using one over another? (I know both are "correct" in syntax and both work, but which is preferred?)
Upvotes: 4
Views: 70
Reputation: 237040
I'd go for the second one every time. Besides the important fact that it makes little sense to stick half-constructed objects in your public interface (even if you don't yet have a codepath that could expose the bug), the second way is more efficient with zero cost. For every self.thing.otherThing =
, you're sending a minimum of two messages, and more if you someday get KVO involved. There is absolutely no benefit to that indirection — it doesn't make your code read more clearly, it doesn't make it more concise, it doesn't make it safer, nothing.
Upvotes: 2
Reputation: 1586
I prefer the second method. The only real benefit is reducing stress on the autorelease pool, which is minimal if only initializing a few objects like this. It's unlikely that you are modifying that property on another thread that could potentially cause unintended behavior if using the first method, but I suppose that is a risk. To me it also seems to be the difference of building a component and then installing it versus installing an unfinished component then building it in place.
Upvotes: 4