O'Reilly logo

iOS 5 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.3. Populating a Table View with Data

Problem

You would like to populate your table view with data.

Solution

Conform to the UITableViewDataSource protocol in an object and assign that object to the dataSource property of a table view.

Discussion

Create an object that conforms to the UITableViewDataSource protocol and assign it to a table view instance. Then, by responding to the data source messages, provide information to your table view. For this example, let’s go ahead and declare the .h file of our view controller, which will later create a table view on its own view, in code:

#import <UIKit/UIKit.h>

@interface Populating_a_Table_View_with_DataViewController
           : UIViewController <UITableViewDataSource>

@property (nonatomic, strong) UITableView *myTableView;

@end

Now let’s synthesize our table view:

#import "Populating_a_Table_View_with_DataViewController.h"

@implementation Populating_a_Table_View_with_DataViewController

@synthesize myTableView;

...

In the viewDidLoad method of our view controller, we will create the table view and will assign our view controller as its data source:

- (void)viewDidLoad{ [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; self.myTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain]; self.myTableView.dataSource = self; /* Make sure our table view resizes correctly */ self.myTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; [self.view addSubview:self.myTableView]; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required