I have a subclass of UIViewController with an NSMutableArray as a property to use as the data source for a UITableView. I create an instance of the class in my storyboard.
I want to populate the array with the addObject: method but if I try, the array always returns (null).
I read that @synthesize doesn’t init the array and I might need to override -init and init the NSMutableArray there but -init never gets called.
How is this supposed to work?
You need to create an instance of
NSMutableArrayand assign it to the property.Since the object with the property is a
UIViewControllercreated in a storyboard, you can do it in a few different places. You can overrideinitWithCoder:, orawakeFromNib, orviewDidLoad.If you override
initWithCoder:, it is imperative that you call thesupermethod.If you do it in
viewDidLoad, the array won’t be created until the view is loaded, which doesn’t have to happen right away.I recommend doing it in
awakeFromNib:Another option is to just create the array lazily by overriding the getter method of the property:
If you do this, it is very important that you always access the array using the getter method (
self.myArrayor[self myArray]) and never by accessing the instance variable (_myArray) directly.