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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…