views:

158

answers:

2

In my iPhone app I have a UIViewController that has a UITableView and another UIView, in its xib file, the view of the xib contains both the UITableView and the other UIView. Both view are linked as IBOutlets to the appropriate views in the xib file. When I want to set the data source programmatically for the UITableView I create a method like this in the UIViewController:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil tableDataSource:(id)dataSource{
if ((self = [self initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
    // Custom initialization
    self.inventoryTableView.dataSource = dataSource;
    //[self.inventoryTableView reloadData];
}
return self;}

and then I implement the following methods in another class of mine, let's call it B:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

Finally I alloc+init B and pass the instance to the method initWithNibName:bundle:tableDataSource: creating the UIViewController. All the views appear in the simulator but the data source methods appear not to be called. I do something similar with another controller and works, but it is a UITableViewController and the the TableView is the controller's view. Is it possible that being a subview i have to set the data source in another method different from the initWithNib?

UPDATE: By putting the datasource assignation in the viewDidLoad: method I was able to solve it. It appears to me that even after calling [self initWithNibName:nibNameOrNil bundle:nibBundleOrNil] the subViews of the main view are not properly inited

A: 

Take a look at this answer, I think it's similar to what you're proposing with using "B" as the external datasource for the controller.

http://stackoverflow.com/questions/2097864/simple-way-to-separate-uitableview-datasource-and-delegate-from-main-uiviewcontro

chilitechno.com
I read that and the link inside of it too.I do not want to pass from IB (and let it istanziate my data source class) I just want to do it programmatically (and I already did for another similar situation as said in the post).
rano
I seemed to solve it by setting the data source in the `viewDidLoad:` method. But still I do not understand why it works for the other class
rano
A: 

As said in the update and in a comment, I resolved by changing where to set the delegate/data source because it was necessary to wait for the tableView to be allocated and inited. It appears to me that as a subview it gets allocated/inited later than the main view of the class

rano