Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I be using awakeFromNib or initWithCoder here?

My initial view controller is loaded, and I need an NSArray to be init'd, should I take care of this in an awakeFromNib method or an initWithCoder: method? awakeFromNib seems to work nicer, as I don't need to return anything, but it works as nib files were what used to be used right? I don't want to use a method that will break soon.

And would initWithCoder: just look like:

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super initWithCoder:decoder]) {
        self.articles = [[NSMutableArray alloc] init];
    }

    return self;
}
like image 359
Doug Smith Avatar asked Mar 19 '13 18:03

Doug Smith


1 Answers

The point of -awakeFromNib is so that you can do init stuff when you can be sure that all your connections to other objects in the nib have been established.

The nib-loading infrastructure sends an awakeFromNib message to each object recreated from a nib archive, but only after all the objects in the archive have been loaded and initialized. When an object receives an awakeFromNib message, it is guaranteed to have all its outlet and action connections already established.

Don't forget to call super.

It is unlikely to go away any time soon, and if it did so much code uses it that the transition period would be long. Yes its name comes from the old "nib" file format but this stack overflow question clears up the differences in the file extensions.

So in summary either method will work for you as you are setting an internal instance variable for the class. Note that inside init methods (including -initWithCoder) it may not be safe to use your setter methods in case setters rely on the class being fully initialised (source WWDC 2012 video moving to modern objective-c). An example would be setting a property that references another object in the nib file.

In UIViewController subclasses -initWithCoder is only called when loading from a storyboard. As -awakeFromNib is called whether you use storyboards or not it might make more sense to use that.

Another pattern you could consider is the lazy-getter:

- (NSMutableArray *)articles{
    if (_articles){
        return _articles;
    }
    _articles = [[NSMutableArray alloc] init];
    return _articles;
}

The benefit of this approach is that if you wanted to do further setup to the array you can easily discard the array when you don't need it anymore and the next time you access the property you have a fresh one again.

like image 91
jackslash Avatar answered Oct 23 '22 05:10

jackslash