Questions regarding P.133 and P.134


Hello, everyone!
I am new to Objective-C and iOS programming so please forgive me for asking noob questions :wink:

I am confused when I read P.133 and P.134,
BNRHypnosisViewController.m and BNRReminderViewController.m use different codes in their InitWIthNibName: bundle: method

I tried to copy BNRHypnosisViewController’s code in BNRReminderViewController, modified the title name and image filename accordingly then compile and run
the simulator showed the same result as before.

Since either way works, here are my questions:
Q1. why BNRReminderViewController needed to use a local variable to hold the reference to self.tabBarItem while BNRHypnosisViewController didn’t?
Q2. why don’t 2 methods use same code?


[code]- (instancetype)initWithNibName:nibNameOrNil
bundle:(NSBundle *)nibBundleOrNil
self = [super initWithNibName:nibNameOrNil

    // Get the tab bar item
    UITabBarItem *tbi = self.tabBarItem;
    // Give it a label
    tbi.title = @"Reminder";
    // Give it an image
    UIImage *i = [UIImage imageNamed:@"Time.png"];
    tbi.image = i;

return self;



[code]- (instancetype)initWithNibName:(NSString *)nibNameOrNil
bundle:(NSBundle *)nibBundleOrNil
self = [super initWithNibName:nibNameOrNil
bundle:(NSBundle *)nibBundleOrNil];
// Set the tab bar item’s title
self.tabBarItem.title = @“Hypnotize”;

    // Create a UIImage from a file
    // This will use Hypno@2x.png on retina display devices
    UIImage *i = [UIImage imageNamed:@"Hypno.png"];
    // Put that image on the tab bar item
    self.tabBarItem.image = i;
return self;


Thank you and have a nice day!


As you noted, BNRReminderViewController didn’t need to use a separate local variable; it just did so as a convenience. Sometimes it’s harder to read code that keeps going down the same chain, changing only the last item.

this.that.theOther.x = 1;
this.that.theOther.y = 2;


NSPoint p = this.that.theOther;
p.x = 1;
p.y = 2;

Just guessing, I’d guess the above was the intent with BNRReminderViewController.

If by “same code” you mean “same technique”…they could. If nothing else, it just emphasizes that there are multiple ways to do this; pick the one that feels most comfortable for you.

The fact that you’re asking this type of question is good: it means you’re not just typing in what you see, but actively thinking about the code and understanding it.


Thank you gc3182, your explanation is very helpful to me
I did guess there might be some convention behind it that the book used different “techniques”(thank you for suggestion)
Even the result of two different techniques turned out to be the same, I wondered if there were some differences behind the scene…
However your explanation seems to be reasonable. Thank you!

Thank you for your kind word, this is very encouraging to me :slight_smile: