Search
Rich's Mad Rants
Powered by Squarespace

Creating iOS 5 Apps Discussion > Chapter 6 - How does init get called?

Hi Rich,

Steadily working my way through the book again and I reached another stumbling block. My program wasn't running correctly and I found the program was just quitting when TabBarController.m called "self.weightHistory = [[WeightHistory alloc] init];". When I look at WeightHistory.h, I see that we only overrode initWithURL, not init. In other languages, if I needed multiple init methods I would typically create each init method and have each one call the most comprehensive init method in the group with various default values. Should I follow the same process here and create an "init" method that calls "initWithURL"? If I don't create an init method, my program seems to just quit unexpectedly. Any ideas?

Thanks again for the awesome book,
AJ

February 29, 2012 | Unregistered CommenterAJ

Sorry to take so long to respond. I've been traveling, and I'm just now catching up.

I think you're on the right track...

Specifically, to have the chain of initializations work properly, you need to follow a few rules.

1) Each class should have a single, designated initializer. The designated initializer is responsible for any custom initialization or setup required.

2) The designated initializer must call the superclass's designated initializer. You always reassign the self variable in this step. For example, for any class subclassing NSObject, you would have a line that says:

self = [super init];

3) All other initializers must call the designated initializer.

4) If your class's designated initializer is different than the superclass's designated initializer, then you must override the superclass's designated initializer and have it call your designated initializer.

So, our WeightHistory object follows these rules. It overrides the superclass's designated initializer, so we can skip step #4, and it doesn't have any additional initializers, so we can skip step 2. The resulting method should look like this:

- (id)init
{
self = [super init];
if (self) {
// Set initial defaults.
_defaultUnits = LBS;
_weightHistory = [[NSMutableArray alloc] init];
}
return self;
}

However, I don't think any of that fixes your problem. I'm not sure about the reference to initWithURL. I don't remember ever writing that method--and doing a quick search through the book, I didn't find any references to it. Was that an autocomplete mistake? If not, please give me a reference to the page and I'll look into it more.

-Rich-

March 7, 2012 | Registered CommenterRichard Warren