Reputation: 727
I have spotted an example in book: "iOS4 Programming Cookbook" that I can't understand:
Tray *newTray = [[Tray alloc] initWithPrinter:self];
paperTray = [newTray retain];
[newTray release];
I can't understand why we need a newTray variable. Why we couldn't just use this code:
paperTray = [[Tray alloc] initWithPrinter:self];
Tray is just a Model Class. paperTray - property: Tray *paperTray;
Upvotes: 2
Views: 84
Reputation: 1257
The author was probably copying a very common pattern that actually makes sense when you're dealing with properties:
Tray *newTray = [[Tray alloc] initWithPrinter:self];
self.paperTray = newTray;
[newTray release];
Now this is very different! If paperTray
is a property that was declared with (retain)
(and most properties are) then the second line will actually call a setter that retains the given object again. The above three lines are still excessive, but are actually a common pattern that you'll see in a lot of code (including some Apple's example code, iirc). The other variable makes it clear that you're balancing the initial alloc
with a release
, since the property secretly retains it again.
You could write this more concisely like this:
self.paperTray = [[Tray alloc] initWithPrinter:self];
[self.paperTray release];
or even
self.paperTray = [[[Tray alloc] initWithPrinter:self] autorelease];
but these don't really save you much effort, and are probably more, not less, confusing if you don't know how properties work. So I usually use the three-line pattern that introduces an extra variable. It's idiomatic.
Again, though, this only makes sense with retained properties. In the code in your post, there is no reason whatsoever to use an extra variable. Either the author was using the pattern without understanding its purpose, or initially was using properties and then changed it without much thought.
Upvotes: 1
Reputation: 2183
You don't need the newTray
variable at all. The alternate code you posted would be equivalent, and less verbose.
The author may have included the other variable just to make it clear precisely what [[Tray alloc] initWithPrinter:self]
does.
Upvotes: 6