Why create a new BNRItem upon return from Detail


#1

In the exercise within the viewWillDisappear method of BNRDetailViewController, the authors have us creating a new BNRItem called item and setting it to self.item. We then update item with the data from the user fields. Of course this works fine; however, I am wondering why we create a new BNRItem pointer rather than just use self.item? To illustrate:

The book says do this within viewWillDisappear:

    BNRItem *item = self.item;
    item.itemName = self.nameField.text;
    item.serialNumber = self.serialNumberField.text;
    item.valueInDollars = [self.valueField.text intValue];

Why not do this:

    self.item.itemName = self.nameField.text;
    self.item.serialNumber = self.serialNumberField.text;
    self.item.valueInDollars = [self.valueField.text intValue];

#2

It’s just a matter of preference.


#3

[quote=“C6silver”]In the exercise within the viewWillDisappear method of BNRDetailViewController, the authors have us creating a new BNRItem called item and setting it to self.item. We then update item with the data from the user fields. Of course this works fine; however, I am wondering why we create a new BNRItem pointer rather than just use self.item? To illustrate:

The book says do this within viewWillDisappear:

    BNRItem *item = self.item;
    item.itemName = self.nameField.text;
    item.serialNumber = self.serialNumberField.text;
    item.valueInDollars = [self.valueField.text intValue];

Why not do this:

self.item.itemName = self.nameField.text; self.item.serialNumber = self.serialNumberField.text; self.item.valueInDollars = [self.valueField.text intValue]; [/quote]

The first line (BNRItem *item = self.item;) does not create a new item; it is just a temporary (local) variable. The two code listings you provided are actually 100% identical. To create a new item, you would need to alloc-init a BNRItem (or use the +randomItem class method, which itself alloc-inits a new BNRItem).

Let me know if I need to clarify anything. :slight_smile:


#4

To further talk about this …

There are other examples of creating pointers instead of sending messages directly.

The next section in this chapter explains how to change the text on the navigation item. They create a pointer. My first instinct would have been to send a message directly

UINavigationItem *navItem = self.navigationItem navItem.title = @"Homepwner"

I would have tried the following on first instinct

Can someone explain the full difference between this. Is there any difference? An extra pointer. Code readability. Easier to debug.