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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With