开发者

Is it possible to programmatically set a UITableViewController's dataSource?

I've created an application using the Navigation-based template in Xcode. I've also created a class that implements the UITableViewDataSource protocol and would like to use it for that UITableView in the RootViewController.

I've tried setting the dataSource property in viewDidLoad, and in all flavors of initializers, but I can't get it to work.

How can I do this?

Currently I'm doing the following:

- (void)viewDidLoad {
    [super viewDidLoad];

    // The Navigation Controller uses this to display the title in the nav bar.
    self.title = @"Names";

    // Little button with the + sign on the right in the nav bar开发者_运维问答
    self.navigationItem.rightBarButtonItem = 
        [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(showAddNameScreen)];

    // Set the data source and reload.
    [self.tableView setDataSource:[DataAcceess sharedInstance]];
    [self.tableView reloadData];
}

But the table just stays empty and the data source methods never get called (numberOfRowsInSection and cellForRowAtIndexPath)

Edit: My sharedInstance was buggy and returning nil. No methods were ever called on it.


Try

[self.tableView setDataSource:myDataSource];

From within the UITableViewController subclass (ie self).


After setting the dataSource, did you call reloadData to make the table view use the new data source?


Does your table data source return a non-zero number of rows?


The issue was that my sharedInstance method had a bug where it could return nil. Since sending messages to nil is silently ignored nothing was ever called on my class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜