Reputation: 157
Here is a sample scenario:
You have a view controller "ItemsViewController" that lists "Items" in a UITableView. This is all set in a navigation controller that will let you change the title of the UINavigationItem title property. I am going through a book that will remain nameless that accesses this property 2 ways on the same page and I'm not sure why;
USING A POINTER
UINavigationItem *n = [self navigationItem];
[n setTitle: @"Title"];
SENDING OBJECT MESSAGE DIRECTLY
[[self navigationItem] setTitle:[item itemName]];
I understand how both of these work (correct me if I'm wrong) the pointer points to the navigationItem and when you change the property it changes it in the navigationItem
otherwise you send the navigationItem the setTitle message with an updated string.
My real question however is why you would do this one way vs the other way in any situation? Is there a time where one of these ways has an advantage?
Upvotes: 1
Views: 99
Reputation: 47759
When you do the second, the compiler generates a hidden temporary variable. In the first case you define the temporary variable for the compiler.
It's often best to break "daisy chained" operations down into sequential temp assignments (on separate lines, please!) to make the sequence clearer and to make it easier to debug.
With the operations broken apart (and on separate lines!) it becomes easy to set breakpoints, examine intermediate results, etc. And there is no "downside" in terms of performance.
(It is rarely justified to place multiple statements on the same line, and there are many reasons to not do that.)
Upvotes: 0
Reputation: 318955
The end results is the same. Another option would be:
self.navigationItem.title = item.itemName;
The benefit of using intermediate variables is readability and debugging. Many times people post code with 5 levels of nested method calls and then ask why it doesn't work. By splitting those calls into separate lines using intermediate variables, you can more easily read and debug the code. But for this example, there is little benefit.
It's really helpful when digging deep into some collection hierarchy.
Upvotes: 3
Reputation: 119041
They're identical really. The only difference is that in the first case you hold a named local reference to the object and in the second case you don't.
To choose between the 2 forms is part personal preference and part how many methods you're going to call on the object. If you're just going to call one method then the only real benefit of the named local variable is that it makes debugging easier.
Upvotes: 1