2

I'd like to have a separate class that conforms to UITableViewDataSource protocol and works with data objects. Where is better to keep, allocate and initialize the instance of this class? If I do this in ViewDidLoad method of Table View Controller subclass, that connected to Storyboard, the instance of data source is deallocated after method ViewDidLoad is finished.

- (void)viewDidLoad
{
    [super viewDidLoad];
    MyTableViewDataSource* myDataSource = [[MyTableViewDataSource alloc] init];
    self.tableView.dataSource = myDataSource;
} // self.tableView.dataSource is deallocated

Will it be better solution to create a strong property of data source object in of Table View Controller subclass, that connected to storyboard and than allocate and initialize instance of data source in ViewDidLoad?

@interface MyTableVC : UITableViewController
@property  (strong, nonatomic)  MyTableViewDataSource *myDataSource;
@end

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.myDataSource = [[MyTableViewDataSource alloc] init];
    self.tableView.dataSource = myDataSource;
}
Bannings
  • 10,376
  • 7
  • 44
  • 54
Julian D.
  • 321
  • 4
  • 11

1 Answers1

3

The reason it's being deallocated is because the UITableView does not retain it:

@property(nonatomic, assign) id< UITableViewDataSource > dataSource
                     ^^^^^^

This is normal with delegates, in order to avoid retain cycles.

Therefore if you want to create a new object to act as your data source, you will need to retain it, as per your 2nd code snippet.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242