iPhone TableView control
Tuesday, November 3, 2009 at 9:57PM Smart phones popularity have increased since the introduction of the iPhone. The iPhone SDK and the Android SDK are by far the most compelling mobile platforms in the mobile space. In this article I explore the most common control on the iPhone by using a UITableView to display a list of books. The Book class is shown below.
@interface Book : NSObject {
NSString* author;
NSNumber* price;
NSString* title;
NSString* description;
NSString* image;
}
@property(nonatomic, retain) NSString* author;
@property(nonatomic,retain) NSString* description;
@property(nonatomic,retain) NSString* title;
javascript:noop()@property(nonatomic, retain) NSNumber* price;
@property(nonatomic, retain) NSString* image;
@end

For this example I will use the default user interface created by the project template. Notice that the template created a RootViewController.h and RootViewController.m files. Make sure that the RootViewController class implements the UITableViewDataSource and UITableViewDelegate protocols and has an NSArray of Book objects.
@interface RootViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate> {
NSArray* books;
}
@end

In the above code snippet when the view is loaded I get the path for the books.plist file which contains the sample data that will be displayed on a table view. The plist file contains an array of dictionaries here is a snippet of what it contains.

The plist is loaded into the theBooks array and I iterate through the array, create a Book object and add it to the mutableArray. After all the Book objects are loaded into the mutableArray I initialize the books array on line 32.

In order to display data on the table view the following UITableViewDataSource protocol methods must be implemented:
- - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView.
- On line 85 the numberOfSectionsInTableView method returns 1 for the number of sections in the table view.
- - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section.
- On line 92 the number of rows is returned which is the number of entries in the books array.
- - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPat *)indexPath.
- Line 106 - // Configure the cell.
- Line 107 -
Book* book = [books objectAtIndex:indexPath.row]; - Line 108 -
cell.textLabel.text = book.author; - Line 109 -
cell.detailTextLabel.text = book.title; - Line 111 -
cell.imageView.image = [UIImage imageNamed:book.image];
Here is the application running in the simulator.

Download the xcode source code.
TableView,
iPhone SDK in
Mobile 
Reader Comments (1)
your tutorial is great but what should i do if i wan to implement a search bar?i have tried many ways but i can't seems to get to the correct way..perhaps it's becoz i just started on iphone so was very new to all these..appreciate your help!