Consider a situation where you have an object in a storyboard file linked up to an IBOutlet, such as the following.
@property (nonatomic, strong) IBOutlet UIImageView *imageView;
Left to its own devices, the ViewController will happily load and display the correct image inside the correct frame, etc, as determined in Interface Builder.
However, if the following code is added to the View Controller’s viewDidLoad method, an (apparently) identical outcome is achieved.
- (void)viewDidLoad {
_imageView = [[UIImageView alloc] init];
//...
}
Does this mean the programmatic alloc-initing of IBOutlets is completely optional? Or is the addition of this line achieving a slightly different outcome?
I’m asking because I have always added the alloc-init in the implementation, then in my latest project I forgot about it, and to my surprise, it still worked exactly as intended.
A storyboard or xib file is a serialisation of the objects contained within. When the storyboard is loaded, all of the objects are instantiated (using
initWithCoder:, since we are deserialising them). This does the same job as allo/init, with the addition of setting all of the properties of the object that are defined in the xib.The xib contains enough information about your image view to fully create it. If you then alloc/init a new image view and assign it to the variable that was used for the outlet, you are just replacing the object that was created from the storyboard, which is pretty pointless, since your outlet now points to nothing on the screen.
In summary – alloc/init ing every outlet isn’t optional, it’s wrong.