If you want to display a list of items in your app, then UITableView object is your answer. The object makes it really easy to display a list of items. In this tutorial, you will learn how to set up a simple table view. Click on “Read more” to get started.

Introduction
In most cases, the requirement is to select an item from the list displayed and then load the details of the selected item in a detail view. UITableView is only responsible for the list of items it displays, the navigation that happens between the list of items and the detail view is handled by the UINavigationController. So the table view always works with the navigation controller and viceversa. This is how the final app looks like

Creating the project
Create a new XCode project by clicking on File -> New Project -> (Under iPhone OS) select “Navigation-Based Application”, give it a name and save the project. I have named my project “TableView”. The project template “Navigation-Based Application” will give you a navigation controller and a table view tied together, so you do not have to set it up manually.

Data Source
Since we want to display not one or two but a list of items in the table view, we need some kind of a data source to hold our data and something which we can pass it on to the table view so it can use it. This data source can come from anywhere XML Files, Databases, or an array. To learn how to use SQL Lite databases read my SQL Lite tutorial series here. To keep this tutorial simple, I will choose a NSMutableArray as the data source for the table view. You can fill this array from XML files or SQLLite database. The array will be populated with string objects and not custom objects to keep the tutorial less confusing. Read my SQL Lite tutorial series to understand how to use custom objects with the table view.

The first thing to do is to build the data source, populate it with the items we need to display in the table view. Let’s build our data source in viewDidLoad method of the RootViewController which is called when the view is loaded. This is how the header file and viewDidLoad method in the implementation file looks like

#import 
 
@interface RootViewController : UITableViewController {
 
NSMutableArray *listOfItems;
}
 
@end
 
//viewDidLoad method declared in RootViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
 
//Initialize the array.
listOfItems = [[NSMutableArray alloc] init];
 
//Add items
[listOfItems addObject:@"Iceland"];
[listOfItems addObject:@"Greenland"];
[listOfItems addObject:@"Switzerland"];
[listOfItems addObject:@"Norway"];
[listOfItems addObject:@"New Zealand"];
[listOfItems addObject:@"Greece"];
[listOfItems addObject:@"Rome"];
[listOfItems addObject:@"Ireland"];
 
//Set the title
self.navigationItem.title = @"Countries";
}
 
//dealloc method declared in RootViewController.m
- (void)dealloc {
 
[listOfItems release];
[super dealloc];
}

Array “listOfItems” is declared in RootViewController.h file and is of type NSMutableArray, it is also released in the dealloc method as shown above.

In viewDidLoad method, we allocate memory and initialize the array and add 8 objects to it. The view of the navigation bar is set to “Countries”. Now somehow we need to tell the table view to display the items in the array.

Customize the number of rows in the table view
The first thing we have to do is, tell the table view how many rows it should expect and this is done in tableView:numberOfRowsInSection. This method returns an integer which is the number of rows that the table view will display. Since our array consists of 8 objects, we will pass the count message to the array. This is how the code looks like

//RootViewController.m
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [listOfItems count];
}

Display data in a table cell.
Now that the table view knows how many rows to display, we need to display the actual text which goes in a table view cell. The table view is made of table rows and rows contains table cell. This is done in tableView:cellForRowAtIndexPath which is called n number of times, where n is the value returned in tableView:numberOfRowsInSection. The method provides indexPath which is of type NSIndexPath and using this we can find out the current row number the table view is going to display. This is how the code looks like

//RootViewController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 
static NSString *CellIdentifier = @"Cell";
 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
 
// Set up the cell...
NSString *cellValue = [listOfItems objectAtIndex:indexPath.row];
cell.text = cellValue;
 
return cell;
}

In the code above, we first initialize the cell if required. Then get the string from the array, by passing objectAtIndex method to the receiver, with the current row number. The “cellValue” is then set to the text of the cell and the cell is returned. Run your application to see the eight rows in the UITableView.

Conclusion
UITableView really makes it easy to display list of items, by configuring few simple methods. I hope this tutorial helped you in getting started. I know this tutorial is really simple but this way I really get to concentrate on one problem at a time. In my next tutorial,I will show you how to load a detail view and pass data to it.

Happy Programming,
iPhone SDK Articles


Attachments

Suggested Readings

 

24 Responses to UITableView – Creating a Simple Table View

  1. Mishti says:

    Hiiiiiii
    Plz give me idea about creation of row and column. Can u write blog for create a row and column.
    For Example :-
    Number | Name |
    1 | khush |
    2 | Rose |
    3 | nisha |

    Plz can u write about this type creation of UITableView…….

    Thanx

  2. Abhinandan says:

    Hi

    This worked f9 for navigation based app(template),but it’s not working when i try it wid view based app…Can ny1 suggest me sumthing?

    Thanks

  3. Bravo says:

    I get warning at :

    // Set up the cell…
    NSString *cellValue = [listOfItems objectAtIndex:indexPath.row];
    cell.text = cellValue;

    return cell;

    at :

    cell.text = cellValue; -> warning setText is deprecated

  4. Gary Cobb says:

    I am getting this error too…
    Rootviewcontroller.h
    it says method definition not in @implementation context
    Is there a fix for this?
    Thanks

  5. Brian Pearson says:

    Hey guys this worked great for me but i was just wondering how to edit the info of the countries? So that once the country name is clicked on an image and a description will show up?

    thanks

    • JK says:

      I don’t have a tutorial right now showing how to do that. I will write one.

      What you have to do is, create a new view with all the fields on it to edit a country. Once the user makes the changes to the view, you have to save those changes back to your data source.

  6. sdfsd says:

    Nevermind i have solved it THANK YOUUUUUU

  7. sdfsd says:

    This came up with an error in Rootviewcontroller.h
    it says method definition not in @implementation context
    how do i fix this?

    • JK says:

      I downloaded the source code from this article and I was able to compile it successfully. I did have to change the target sdk and change cell.text to cell.textLablel.text because “setText” selector is depricated. It sounds like you have a selector in .m file which is not declared in the header file. Can you provide some more details on the error?

      • sdfsd says:

        In my rootviewcontroller.h and detailviewcontroller.h files it said there is an error:

        - (void)viewDidUnload { Expected ‘;’ token before ‘{‘

        there are 4 errors in all.

        • JK says:

          viewDidLoad selector should be implemented in RootViewcontroller.m file. It sounds like you have implemented this method in the header file.

          I think the code example at the top of this article is a bit confusing. It combines code from .h and .m files.

          In the future, I will create different code snippets for different files.

  8. Amos Lecato says:

    I’d come to okay with you here. Which is not something I usually do! I love reading a post that will make people think. Also, thanks for allowing me to speak my mind!

  9. Anonymous says:

    >Hey,

    in listofitem i have added 15 items

    But while loading it displays only first 10 items

    what the problem..

    help me pls..

  10. iPhone SDK Articles says:

    >@Michael

    that is a big oops, I will change it as soon as possible.

    Happy Programming,
    iPhone SDK Articles

  11. Anonymous says:

    >Hi

    Thanks. But you left this bit out of your tutorial (which I found in the source file). Perhaps you should include it in the above tutorial so that there are no errors.

    // Set up the cell…
    NSString *cellValue = [listOfItems objectAtIndex:indexPath.row];
    cell.text = cellValue;

    return cell;

  12. Michael says:

    >Excellent tutorial: my only quibbles are that you could use arrayWithObjects to shorten the section where you add items, and I believe that Rome is just a city, not a country :-)

  13. Jan Verhulst says:

    >BIg big thanks for these tutorials! You’re great man! Really good explanation.

    I’m doing this research for school, and you’re really helping me :)

  14. iPhone SDK Articles says:

    >@Julien I think this tutorial http://www.iphonesdkarticles.com/2009/01/uitableview-loading-detail-view.html answers your question.

    Please let me know if I can be of any more help.

    Happy Programming,
    iPhone SDK Articles

  15. Julien says:

    >This is a great tutorial. Now, what would I do if I wanted to load a second view? I know it would involve doing something with the interface builder, but what exactly?

    Thanks

  16. iPhone SDK Articles says:

    >@Thiago

    Good to know the tutorials helped you.

    Yes, you are right “cellValue” should be released. I will update the code. Good catch :)

    Happy Programming,
    iPhone SDK Articles

  17. Thiago says:

    >Thanks for posting, very easy to follow and it worked without any glitches..

    just a quick question, shouldn’t the cellValue string be released at the enf of the cellForRowAtIndexPath function?

    Now on to part II! :)

    Thiago

  18. Anonymous says:

    >Thank you! I have worked through several other tutorials, but after this one I finally understand!

  19. Anonymous says:

    >Thanks for posting this tutorial!

    I’ve read so many tutorials on how to handle a UITableView but they all just say like “type this and it’ll do that”.
    You go along every function and explain it.

    So great work, thanks a lot!