iOS Programming Tutorial: Create a Simple Table View App

Is it fun to create the Hello World app? In this tutorial, we’ll work on something more complex and build a simple app using Table View. If you haven’t read the previous tutorial about the iOS programming basic, check it out first before moving on.

First, what’s a Table View in iPhone app? Table View is one of the common UI elements in iOS apps. Most apps, in some ways, make use of Table View to display list of data. The best example is the built-in Phone app. Your contacts are displayed in a Table View. Another example is the Mail app. It uses Table View to display your mail boxes and emails. Not only designed for showing textual data, Table View allows you to present the data in the form of images. The built-in Video and YouTube app are great examples for the usage.

UITableView Sample App

Sample Apps Using Table View

Create SimpleTable Project

With an idea of table view, let’s get our hands dirty and create a simple app. Don’t just glance through the article if you’re serious about learning iOS programming. Open your Xcode and code! This is the best way to study programming.

Once launched Xcode, create a new project for “Single View application”.

Choose Xcode Template

Xcode Project Template Selection

Click “Next” to continue. Again, fill in all the required options for the Xcode project:

  • Product Name: SimpleTable – This is the name of your app.
  • Company Identifier: com.appcoda – It’s actually the domain name written the other way round. If you have a domain, you can use your own domain name. Otherwise, you may use mine or just fill in “edu.self”.
  • Class Prefix: SimpleTable – Xcode uses the class prefix to name the class automatically. In future, you may choose your own prefix or even leave it blank. But for this tutorial, let’s keep it simple and use “SimpleTable”.
  • Device Family: iPhone – Just use “iPhone” for this project.
  • Use Storyboards: [unchecked] – Do not select this option. We do not need Storyboards for this simple project.
  • Use Automatic Reference Counting: [checked] – By default, this should be enabled. Just leave it as it is.
  • Include Unit Tests: [unchecked] – Leave this box unchecked. For now, you do not need the unit test class.
SimpleTable Project Setting

SimpleTable Project Options

Click “Next” to continue. Xcode then asks you where you saves the “SimpleTable” project. Pick any folder (e.g. Desktop) to save your project. As before, deselect the option for Source Control. Click “Create” to continue.

Select Xcode Project Folder

Pick a Folder to Save Your Project

As you confirm, Xcode automatically creates the “SimpleTable” project based on the options you’ve provided. The resulting screen looks like this:

SimpleTable Xcode Main Screen

Main Screen of SimpleTable Project

Designing the View

First, we’ll create the user interface and add the table view. Select “SimpleTableViewController.xib” to switch to the Interface Builder.

SimpleTable Interface Builder

Interface Builder for SimpleTable Project

In the Object Library, select the “Table View” object and drag it into the view.

Xcode Object Library Table View

Your screen should look like below after inserting the “Table View”.

SimpleTable Table View Added

Run Your App for the First Time

Before moving on, try to run your app using the Simulator. Click the “Run” button to build your app and test it.

SimpleTable Run Button

The Simulator screen will look like this:

SimpleTable Simulator Empty

Easy, right? You already designed the Table View in your app. For now, however, it doesn’t contain any data. Next up, we’ll write some code to add the table data.

Adding Table Data

Go back to the Project Navigator and select “SimpleTableViewController.h”. Append “<UITableViewDelegate, UITableViewDataSource>” after “UIViewController”. Your code should look like below:

1
2
3
4
5
#import <UIKit/UIKit.h>

@interface SimpleTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

@end

The “UITableViewDelegate” and “UITableViewDataSource” are known as protocol in Objective-C. Basically, in order to display data in Table View, we have to conform to the requirements defined in the protocols and implement all the mandatory methods.

UITableViewDelegate and UITableViewDataSource

Earlier, we’ve added the “UITableViewDelegate” and “UITableViewDataSource” protocols in the header file. It may be confusing. What’re they?

The UITableView, the actual class behind the Table View, is designed to be flexible to handle various types of data. You may display a list of countries or contact names. Or like this example, we’ll use the table view to present a list of recipes. So how do you tell UITableView the list of data to display? UITableViewDataSource is the answer. It’s the link between your data and the table view. The UITableViewDataSource protocol declares two required methods (tableView:cellForRowAtIndexPath and tableView:numberOfRowsInSection) that you have to implement. Through implementing these methods, you tell Table View how many rows to display and the data in each row.

UITableViewDelegate, on the other hand, deals with the appearance of the UITableView. Optional methods of the protocols let you manage the height of a table row, configure section headings and footers, re-order table cells, etc. We do not change any of these methods in this example. Let’s leave them for the next tutorial.

Next, select “SimpleTableViewController.m” and define an instance variable for holding the table data.

1
2
3
4
@implementation SimpleTableViewController
{
    NSArray *tableData;
}

In the “viewDidLoad” method, add the following code to initialize the “tableData” array. We initialize an array with a list of recipes.

1
2
3
4
5
6
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Initialize table data
    tableData = [NSArray arrayWithObjects:@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast", @"Hamburger", @"Ham and Egg Sandwich", @"Creme Brelee", @"White Chocolate Donut", @"Starbucks Coffee", @"Vegetable Curry", @"Instant Noodle with Egg", @"Noodle with BBQ Pork", @"Japanese Noodle with Pork", @"Green Tea", @"Thai Shrimp Cake", @"Angry Birds Cake", @"Ham and Cheese Panini", nil];
}

What is an array?

An array is a fundamental data structure in computer programming. You can think of an array as a collection of data elements. Consider the tableData array in the above code, it represents a collection of textual elements. You may visualize the array like this:

tableData array illustration

Each of the array elements is identified or accessed by an index. An array with 10 elements will have indices from 0 to 9. That means, tableData[0] returns the first element of the “tableData” array.

In Objective C, NSArray is the class for creating and managing array. You can use NSArray to create static array for which the size is fixed. If you need a dynamic array, use NSMutableArray instead.

NSArray offers a set of factory methods to create an array object. In our code, we use “arrayWithObjects” to instantiate a NSArray object and preload it with the specific elements (e.g. Hamburger).

You can also use other built-in methods to query and manage the array. Later, we’ll invoke the “count” method to query the number of data elements in the array. To learn more about the usage of NSArray, you can always refer to Apple’s official document.

Finally, we have to add two datasource methods: “tableView:numberOfRowsInSection” and “tableView:cellForRowAtIndexPath”. These two methods are part of the UITableViewDataSource protocol. It’s mandatory to implement the methods when configuring a UITableView. The first method is used to inform the table view how many rows are in the section. So let’s add the below code. The “count” method simply returns the number of items in the “tableData” array.

1
2
3
4
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [tableData count];
}

Next, we implement the other required methods.

1
2
3
4
5
6
7
8
9
10
11
12
13
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"SimpleTableItem";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }

    cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
    return cell;
}

The “cellForRowAtIndexPath” is called every time when a table row is displayed. The below illustration will give you a better understanding about how UITableView and UITableDataSource work.

UITableView and UITableDataSource

How UITableView and UITableDataSource Work Together

Okay, let’s hit the “Run” button and try out your final app! If you’ve written the code correctly, the Simulator should run your app like this:

SimpleTable Simulator Empty

Why is it still blank? We’ve already written the code for generating the table data and implemented the required methods. But why the Table View isn’t shown up as expected?

There is still one thing left.

Connecting the DataSource and Delegate

Like the “Hello World” button in the first tutorial, we have to establish the connection between the Table View and the two methods we just created.

Go back to the “SimpleTableViewController.xib”. Press and hold the Control key on your keyboard, select the Table View and drag to the “File’s Owner”. Your screen should look like this:

SimpleTable Connect Data Source

Connecting Table View with its Datasource and Delegate

Release both buttons and a pop-up shows both “dataSource” & “delegate”. Select “dataSource” to make a connection between the Table View and its data source. Repeat the above steps and make a connection with the delegate.

SimpleTable DataSource Popup

Connect dataSource and delegate

That’s it. To ensure the connections are linked properly, you can select the Table View again. In the upper part of the Utility area, you can reveal the existing connections in the “Connection Inspector” (i.e. the rightmost tab).

SimpleTable Connector Outlet

Show the Connections Inspector

Test Your App

Finally, it’s ready to test your app. Simply hit the “Run” button and let the Simulator load your app:

SimpleTable App

Add Thumbnail to Your Table View

The table view is too plain, right? What about adding an image to each row? The iOS SDK makes it extremely easy to do this. You just need to add a line of code for inserting a thumbnail for each row.

First, download this sample image. Alternatively, you can use your own image but make sure you name it “creme_brulee.jpg”. In Project Navigator, right-click the “SimplyTable” folder and select “Add Files to SimpleTable…”.

SimpleTable Add File

Add Image to Your Project

Select the image file and check “Copy items to destination group’s folder” checkbox. Click “OK” to add the file.

SimpleTable Add File Dialog

Pick your image file and add to the project

Now edit the “SimpleTableViewController.m” and add the following line of code in “tableView:cellForRowAtIndexPath” method:

1
    cell.imageView.image = [UIImage imageNamed:@"creme_brelee.jpg"];

Your code should look like this after editing:

SimpleTable Image Code

Pick your image file and add to the project

The line of code loads the image and saves in the image area of the table cell. Now, hit the “Run” button again and your SimpleTable app should display the image in each row:

SimpleTable App With Image

What’s Coming Next?

It’s simple to create a table view, right? The Table View is one of the most commonly used elements in iOS programming. If you’ve followed the tutorial and build the app, you should have a basic idea about how to create the table view. I try to keep everything simple in this tutorial. In reality, the table data will not be specified directly in the code. Usually, it’s loaded from file, database or somewhere else.

In the next tutorial, we’ll take a look at how you can further customize the table cell. As always, leave me comment and share your thought about the tutorial.

Update: The next tutorial is ready. Check it out!

You May Like These:

  • THD

    Hi Simon,

    I just finished the SimpleTable tutorial. This is great.

    Now, looking forwards to the next tutorial.

    Thank you very much.

  • http://@lienvdsteen Lien

    Hi,

    Just created the SimpleTable. Thank you for sharing this tutorial. I like the style of your tutorials.

    Looking forward to the next one!

    Lien

  • G

    Keep ‘em coming!

  • William

    Great tutorial, Simon. Keep it up!

  • Tom

    Thanks for the tutorial…practical and educational! I look forward to more!

  • SimonZA

    Thanks again for one of your great tutorials!

    While Im having great fun coding along with you, one thing I hope to get from this is full understanding what Im doing, and not just ‘copying’ verbatim.

    An area Im talking about is the big chunk of code we had to add at the “cellForRowAtIndexPath” area.
    I have a vague idea what we are accomplishing here, but it would be extremely helpful if you could just take a brief moment to walk us line for line what it is we were doing. Telling us step by step what each piece of code is needed and used for, and its function in the implementation.

    I know that possibly most of this should seem ‘familiar’ to casually experienced programmers, but for the complete noob like myself who is hoping to learn code and how I could do it myself, it would help a lot.:)

    Again, I appreciate your tutorials! Just that a *little* more explanation with your coding would go a massively long way with understanding what it is we are doing, and how it all works together at the end of the day when performing the magic.:)

    Thanks!!
    Simon

    • http://www.appcoda.com Simon Ng

      Thanks for your nice comment! For the first two tutorials, I’d like to keep thing simple and just explain some of basic concept (e.g. Array) as side note. Later, I’ll give more explanation about code. There are a lot of things to learn about Objective C. The “cellForRowAtIndexPath” is a little complex for beginner. So I’ll write another post to illustrate how it actually works.

      Again, thanks for your great feedback! This really helps me to make this site and the tutorials better.

  • Sue Wright

    Using xcode 4.3.2

    Followed to the letter but getting an error – please help> Error reads. Use of undeclared identifier “tableView”, did you mean UITableView?. It occurs in the following code from the .m file

    // Initialize table data

    tableData = [NSArray arrayWithObjects:@"Boat", @"Insurance", @"Engine", @"Radio", @"Other Equipment", @"Notes",nil];

    – (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
    return [tableData count];
    }

    – (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    static NSString *simpleTableIdentifier = @”SimpleTableItem”;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }

    cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
    return cell;
    }
    }

    • http://www.appcoda.com Simon Ng

      @Sue, could you show me your “SimpleTableViewController.h” file?

      • Sue Wright

        Hi Simon – I have managed to cure the above problem – only to meet another. the viewcontroller.m file is looking for an @end but I am so confused I am not sure where it should go
        so here is the entire file – errors are in CAPITALS

        #import “ViewController.h”
        #import “simpletablecell.h”

        @interface ViewController ()

        @end

        @implementation ViewController – @END IS MISSING IN IMPLEMENTATION COMPLEX

        {
        NSArray *tableData;
        NSArray *thumbnails;
        }

        @synthesize BoatNameLabel1;
        @synthesize BoatModelLabel1;
        @synthesize HullSerialLabel1;
        @synthesize LOALabel1;
        @synthesize DraftLabel1;
        @synthesize BeamLabel1;

        @synthesize InsurerLabel;
        @synthesize PolicyNumberLabel;
        @synthesize ExpireDateLabel;

        @synthesize MainEngineLabel;
        @synthesize MainSerialLabel;
        @synthesize MainServiceLabel;
        @synthesize AuxEngineLabel;
        @synthesize AuxSerialLabel;
        @synthesize AuxServiceLabel;

        @synthesize FixedModelLabel;
        @synthesize FixedSerialLabel;
        @synthesize MMSILabel;
        @synthesize PortableModelLabel;
        @synthesize PortableSerialLabel;

        @synthesize GPSSerialLabel;
        @synthesize FishSerialLabel;
        @synthesize TenderSerial;
        @synthesize TrailerMakeLabel;
        @synthesize TrailerSerialLabel;

        @synthesize TextScroll;

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

        //custom buttons
        - (void)viewDidLoad
        {
        [TextScroll setScrollEnabled:YES];
        [TextScroll setShowsVerticalScrollIndicator:YES];
        [TextScroll setFrame:CGRectMake(0, 55, 320, 320)];
        [TextScroll setContentSize:CGSizeMake(320, 600)];

        [super viewDidLoad];

        // Initialize table data

        tableData = [NSArray arrayWithObjects:@"Boat", @"Insurance", @"Engine", @"Radio", @"Other Equipment", @"Other Notes", nil];

        thumbnails = [NSArray arrayWithObjects:@"jeannea-prestige36-drawing.jpg", @"files.png", @"Honda_BF90.png", @"vhf-radio.png", @"gps.png",@"files.png", nil];

        }

        - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
        {
        return [tableData count];
        }

        - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
        {
        {
        static NSString *simpleTableIdentifier = @”SimpleTableCell”;

        SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
        if (cell == nil)
        {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@”SimpleTableCell” owner:self options:nil];
        cell = [nib objectAtIndex:0];
        }

        cell.nameLabel.text = [tableData objectAtIndex:indexPath.row];
        cell.thumbnailImageView.image = [UIImage imageNamed:[thumbnails objectAtIndex:indexPath.row]];

        return cell;
        }

        // Do any additional setup after loading the view.

        - (void)viewDidUnload – SHOWING UNDECLARED IDENTIFIER VIEW DID UNLOAD

        {

        [self setInsurerLabel:nil];
        [self setPolicyNumberLabel:nil];
        [self setExpireDateLabel:nil];

        [self setTextScroll:nil];

        [self setMainEngineLabel:nil];
        [self setMainSerialLabel:nil];
        [self setMainServiceLabel:nil];
        [self setAuxEngineLabel:nil];
        [self setAuxSerialLabel:nil];
        [self setAuxServiceLabel:nil];

        [self setFixedModelLabel:nil];
        [self setFixedSerialLabel:nil];
        [self setMMSILabel:nil];
        [self setPortableModelLabel:nil];
        [self setPortableSerialLabel:nil];

        [self setBoatNameLabel1:nil];
        [self setBoatModelLabel1:nil];
        [self setHullSerialLabel1:nil];
        [self setLOALabel1:nil];
        [self setDraftLabel1:nil];
        [self setBeamLabel1:nil];

        [self setGPSSerialLabel:nil];
        [self setFishSerialLabel:nil];
        [self setTenderSerial:nil];
        [self setTrailerMakeLabel:nil];
        [self setTrailerSerialLabel:nil];

        [super viewDidUnload];
        // Release any retained subviews of the main view.
        }

        - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
        {
        return (interfaceOrientation == UIInterfaceOrientationPortrait);
        }

        - (IBAction)HideKeyBoard:(id)sender {
        [self.TextScroll resignFirstResponder];
        }

        - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
        {
        return 78;
        }

        @end
        }

        This is the viewconroller.h file

        #import

        @interface ViewController : UIViewController

        @property (strong, nonatomic) IBOutlet UILabel *BoatNameLabel1;
        @property (strong, nonatomic) IBOutlet UILabel *BoatModelLabel1;
        @property (strong, nonatomic) IBOutlet UILabel *HullSerialLabel1;
        @property (strong, nonatomic) IBOutlet UILabel *LOALabel1;
        @property (strong, nonatomic) IBOutlet UILabel *DraftLabel1;
        @property (strong, nonatomic) IBOutlet UILabel *BeamLabel1;

        @property (strong, nonatomic) IBOutlet UILabel *InsurerLabel;
        @property (strong, nonatomic) IBOutlet UILabel *PolicyNumberLabel;
        @property (strong, nonatomic) IBOutlet UILabel *ExpireDateLabel;

        @property (strong, nonatomic) IBOutlet UILabel *MainEngineLabel;
        @property (strong, nonatomic) IBOutlet UILabel *MainSerialLabel;
        @property (strong, nonatomic) IBOutlet UILabel *MainServiceLabel;
        @property (strong, nonatomic) IBOutlet UILabel *AuxEngineLabel;
        @property (strong, nonatomic) IBOutlet UILabel *AuxSerialLabel;
        @property (strong, nonatomic) IBOutlet UILabel *AuxServiceLabel;

        @property (strong, nonatomic) IBOutlet UILabel *FixedModelLabel;
        @property (strong, nonatomic) IBOutlet UILabel *FixedSerialLabel;
        @property (strong, nonatomic) IBOutlet UILabel *MMSILabel;
        @property (strong, nonatomic) IBOutlet UILabel *PortableModelLabel;
        @property (strong, nonatomic) IBOutlet UILabel *PortableSerialLabel;

        @property (strong, nonatomic) IBOutlet UILabel *GPSSerialLabel;
        @property (strong, nonatomic) IBOutlet UILabel *FishSerialLabel;
        @property (strong, nonatomic) IBOutlet UILabel *TenderSerial;
        @property (strong, nonatomic) IBOutlet UILabel *TrailerMakeLabel;
        @property (strong, nonatomic) IBOutlet UILabel *TrailerSerialLabel;

        @property (strong, nonatomic) IBOutlet UITextView *TextScroll;

        - (IBAction)HideKeyBoard:(id)sender;

        @end

        Thank you – your tutorials are the best around.

        • http://www.appcoda.com Simon Ng

          Cool! It’s great you managed to resolve the error and thanks for sharing your code.

          • Sue Wright

            Simon – the above code is the new error I am getting!!! I have highlighted the 2 arers of prolem in CAPITALS I just cannot fathom this one out…

          • http://www.appcoda.com Simon Ng

            @Sue, sorry that I overlooked your comment. By referring to the above code, it looks like that there is a closing bracket after the “@end” statement in the .m file. Please remove it. Make sure that there should be no bracket after the “@end” statement.

            @end
            } <—— remove it

            Also, try to review this method. Look like there is an extra curly bracket:

            - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
            { <—- may need to remove this one. Please review.
            {

          • Sue Wright

            Thank you thank you

    • Dj

      I got the same error as your first error undeclared identifier tableView how did u fix it? Your help would be much appreciated

      Thanks,
      DJ

  • http://www.hye-knudsen.dk Jon Hye-Knudsen

    Hi

    Great tutorials. Thank you

    I am getting an error message when I try to compile this. It complains that “inconsistent instance variable specification” on the NSArray *tableData line and complains about the tableData being non-declared in subsequent uses in the code.
    I just can’t seem to figure out what I am doing wrong.

    • http://www.appcoda.com Simon Ng

      What version of Xcode are you using?

      • http://www.hye-knudsen.dk Jon Hye-Knudsen

        Oops. I just discovered it was Xcode 4.1 I was using. Didn’t think about it, as I guess I was expecting to see some sort of update notification if I wasn’t using the most recent version. Will update now and continue on. Looking forward to it!

        • http://www.appcoda.com Simon Ng

          The default compiler in Xcode 4.1 doesn’t recognize the instance variables defined in the .m file. This is why you got the error. You can resolve the error by upgrade to Xcode 4.3.

  • http://www.iosstuffandreviews.com b2moore

    Thank you for this tutorial, it has helped me a lot. :)

    • http://www.appcoda.com Simon Ng

      Great to hear that!

  • Carlos Corona

    Hello!

    Great tutorial!! I’m following it and I think I’m understanding almost all… but now I’m getting a problem: When I drag over all my list, for some reason I’m getting an error message on line at runtime:

    cel.textLabel.text = [tableData objectAtIndex:indexPath.row];

    This happends only when I’m trying to drag the list over the last element… Is there a way to validate this? Thanks

    • Carlos Corona

      After a little of search, I’ve found that It was a dynamic release problem, because for some reason the Array was been autoreleased too early, so modiffing the line:

      tableData = [NSArray arrayWithObjects:@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast", @"Hamburger", @"Ham and Egg Sandwich", @"Creme Brelee", @"White Chocolate Donut", @"Starbucks Coffee", @"Vegetable Curry", @"Instant Noodle with Egg", @"Noodle with BBQ Pork", @"Japanese Noodle with Pork", @"Green Tea", @"Thai Shrimp Cake", @"Angry Birds Cake", @"Ham and Cheese Panini", nil];

      for

      tableData = [[NSArray arrayWithObjects:@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast", @"Hamburger", @"Ham and Egg Sandwich", @"Creme Brelee", @"White Chocolate Donut", @"Starbucks Coffee", @"Vegetable Curry", @"Instant Noodle with Egg", @"Noodle with BBQ Pork", @"Japanese Noodle with Pork", @"Green Tea", @"Thai Shrimp Cake", @"Angry Birds Cake", @"Ham and Cheese Panini", nil] retain];

      solves the issue, on that case, I’ve added the release code both in methods viewDidUnload and reciveMemoryWarning …

      Hope this helps to anyone with same problem.

      • jaya raj

        Thanks i too faced same prob. Now i got it. Thanks a lot.

  • Pingback: iptips – iphone / ipad / ios / android / mobile / tutorials » How to Add Splash Screen in Your iOS App

  • Alan

    Hello,

    I’m trying to implement this tutorial, and getting a Build error.

    What am I doing wrong? (Thanks for your excellent tutorials).

    My …Controller.m file:
    =======================================================
    //
    // SimpleTableViewController.m
    // SimpleTable
    //
    // Created by Alan Saliwanchik on 5/28/12.
    // Copyright (c) 2012 __MyCompanyName__. All rights reserved.
    //

    #import “SimpleTableViewController.h”

    @interface SimpleTableViewController ()

    @end

    @implementation SimpleTableViewController

    {
    NSArray *tableData;
    }

    - (void)viewDidLoad
    {
    [super viewDidLoad];
    // Initialize table data
    tableData = [NSArray arrayWithObjects:@"Eggs Benedict", @"Mushroom Risotto", @"Full Breakfast", @"Hamburger", @"Ham and Egg Sandwich", nil];

    – (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

    ——> Error Use of undeclared identifier ‘tableView’; did you mean ‘UITableView’? <———

    {
    return [tableData count];
    }
    – (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    static NSSTring *simpleTableIdentifier = @"SimpleTableItem";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIndentifier];

    if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];

    }

    cell.textLable.text = [tableData objectAtIndex:indexPath.row];
    return cell;

    }
    // Do any additional setup after loading the view, typically from a nib.
    }

    - (void)viewDidUnload
    {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    }

    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    {
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    }

    @end
    =======================================================

    • http://www.appcoda.com Simon Ng

      Could you please tell me the build error?

      • Alan

        Pointing to the line

        – (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

        The error message is

        Use of undeclared variable ‘tableView’; did you mean ‘UITableView’?

        • Alan

          Do you have any idea why I’m getting this build error? Thanks in advance. Alan

          • http://www.appcoda.com Simon Ng

            You missed a closing bracket for the viewDidLoad method. In Objective C, make sure all methods are enclosed by a pair of brackets.

  • http://savetrade.idv.tw davidchen

    Thanks again for the tutorial .That Are Better Than YouTube !!!

  • chaitanya

    hello simon,
    the tutorial is awesome for beginners like me. Can you post a tutorial on how to create similar table view without using interface buider?

    hoping to see it soon..

  • http://www.appcoda.com/ios-programming-tutorial-create-a-simple-table-view-app/ vikas

    Nice tutorials ,How to initialize a navigation controller using programming in Xcode 4.3.2 and where to put navigation controller ,becoz its not provide Mainwindows.xib as i previous Xcode’s

  • Pingback: iptips – iphone / ipad / ios / android / mobile / tutorials » Delete a Row from UITableView and Model-View-Controller

  • Sangam

    wow this tutorial really helped
    thanks guyz!!!

    Regard
    Sangam Shrestha

  • Stevie

    Hi Simon,

    This is a great tutorial but i am just having trouble with one problem. I’m using xcode 4.3 and i’m getting this error message at the @implementation saying ‘@end’ is missing in plementation context.
    How can I fix it?

    Cheer Stevie
    #import “SampleTableViewController.h”

    @interface SampleTableViewController ()

    @end

    @implementation SampleTableViewController ERROR: ‘@end’ is missing in plementation context

    {
    NSArray *tableData;
    }

    - (void)viewDidLoad
    {
    [super viewDidLoad];
    // Initialize table data
    tableData = [NSArray arrayWithObjects:@"Egg Benedict", @"Mushroom Risotto", @"Full Breaksfeat", @"Hamburger", @"Ham and Egg Sandwich", @"Creme Brelee", @"White Chocolate Donut", @" Starbucks Coffee", @"Vegetable Curry", @"Instant Noodle with Egg", @"Noodle with BBQ Pork", @"Japanese Noodle with Pork", @"Green Tea", @"Thai Shrimp Cake", @"Angry Birds Cake", @"Ham and Cheese Panini", nil];
    }

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
    return [tableData count];
    }

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    static NSString *simpleTableIdentifier =@”SimpleTableItem”;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }

    cell.textLabel.text = {[tableData objectAtIndex:indexPath.row];
    return cell;
    }

    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    {
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    }

    @end

  • Alan

    My SImple Table with images is working great – thanks!

    When the simulator runs, the table doesn’t scroll vertically in the simulator to show items in my array that don’t initially appear on the screen. Should it scroll?

  • http://www.freemanraushan.wordpress.com Raushan

    Hi Simon!

    I just finished the SimpleTable tutorial. This was amazing! I am new to iOS development and yet, found it quite easy to follow and understood most of the codes.

    Thank you so much.

    I’m so excited to start the next tutorial.

  • manish

    great way of explanation …. :)

  • Pingback: 第三部分:iOS 编程向导:创建一个简单的表视图(Table View)应用程序(2) | EntLib.net 技术分享平台

  • Marvin

    This tutorial is great for an iOS starter.

  • Hugo

    Hey !

    Great tutorial !
    You explained very well what the delegates are used for, helped me a lot to understand !

    Thank you !
    I’m gonna read your next tutorial on tableView customisation, as I hope to achieve something beautiful !

    Keep it up !

  • Pingback: Improve the Recipe App With a Better Detail View Controller | iptips - iphone / ipad / ios / android / mobile / tutorials

  • Dustin

    Hi Simon, I followed everything on the tutorial but when I run on the simulator I got an error “Thread1: signal SIGABRT”. Could you please help me fix it? Thanks!

  • ivan

    thanks for this help!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  • Kevin

    The first time you called to run the simulator I got a table view, but after I followed the instructions and wrote the code, the simulator didn’t show a table view. I even commented out the code to the point where I just added the tableview and the simulator still doesn’t show a tableview. help?

    • Kevin

      Never mind, somehow I inserted a breakpoint….. smh

  • Carlik

    You make simple things that , for me ,are very difficult!!!

  • adsfads

    great job, many thanks!

  • http://twitter.com/Lynnerup1995 Mathias Lynnerup

    Great tutorial!! Thanks!

    But.. i have a prolbem. After doing all the code, i’m trying to connect File’s Owner to the Table View, but instead of DataSource and Delagate it show “-view”. What am i doing wrong??

    Here i the .m file:

    #import “SimpleTableViewController.h”
    @interface SimpleTableViewController ()
    @end
    @implementation SimpleTableViewController{ NSArray *tableData;}
    - (void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. tableData = [NSArray arrayWithObjects:@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast", @"Hamburger", @"Ham and Egg Sandwich", @"Creme Brelee", @"White Chocolate Donut", @"Starbucks Coffee", @"Vegetable Curry", @"Instant Noodle with Egg", @"Noodle with BBQ Pork", @"Japanese Noodle with Pork", @"Green Tea", @"Thai Shrimp Cake", @"Angry Birds Cake", @"Ham and Cheese Panini", nil];}
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return [tableData count];}
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *simpleTableIdentifier = @”SimpleTableItem”; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier]; } cell.textLabel.text = [tableData objectAtIndex:indexPath.row]; return cell;}
    - (void)didReceiveMemoryWarning{ [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}
    @end

  • NIshan

    Awesome

  • Dan

    Thank you so much!! I very greatful

  • patel chirag

    This is really thanks full you.. i m really appreciate for getting this kind of tutorial. it s a really super-duper performance tutorial. Thanks a lot

  • Dana

    gee thanks! :D

  • Qian Yu

    It’s a very good tutorial. Thanks.

  • Arwin

    i worked with your code…its really easy to execute….thanks for ur guidance….

  • http://twitter.com/joped joped

    Awesome tutorial! Thanks very much!

  • Samuel Quiring

    I’m using a newer Xcode (4.5.2). I was ok until “Connecting data source and delegate” After that step when I run the app I get:

    -[UIView tableView:numberOfRowsInSection:]: unrecognized selector sent to instance 0x1f555290

    My routine is:

    @implementation SysCallTestViewController

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
    return [tableData count];
    }

    @end

  • Samuel Quiring

    Found my problem, but now have another. I missed the part where you said: unchecked use storeyboards. When I read your other tutorial that did use storeyboards, I saw how you connected the data source and delegate. So my app no longer faults, but the table view has no text. I put a log statement into tableView:cellForRowAtIndexPath. It displays cell.textLabel.text right before the cell is returned. Everything looks good, the routine got called the correct number of times and returned the correct text. But nothing displays.

  • Steve

    I have been following this tutorial until this point for now. I have a pretty good background of Objective-C and oter programming languages.

    I would recommend that you explain what exactly a class is in your tutorial so your readers are not left clueless of what some of these things are.

    I think it is worth mentioning that NSArray is also a class. And the actions performed by the class, whether the class is one that is predefined like NSString and NSArray, or custom made by the programmer are called methods.

    Again, I just don’t feel that it is complete when the reader may be doing so,etching that he or she does not know what it is he or she is declaring, for instance.

  • preetam

    thanks a lot..

    Your tutorial teaches a lot of basic thing though working since few days…

  • Michael

    Great tutorials. Is there pdf versions available that is a cleaner look for printing? Thanks

    • http://www.simonblog.com Simon Ng

      So far we do not have the pdf version. But we’re working on the eBook that bundles most of the tutorials.

  • Pingback: What I Learn From My 30 Days Coding An iPhone App. | I Do Startup

  • http://www.facebook.com/people/Steve-Taylor/1598234077 Steve Taylor

    Great tutorial. A lot of other tutorials make learning tables overly complicated.

  • wauter

    Your sample image has a typo in the filename, brelee instead of brUlee.

    This tutorial is all kinds of wonderful – I can feel my value in the job market increasing by the paragraph! :-D

  • AThorne

    nice tutorial…Keep it up…

  • manu chadha

    Thanks. My app kept crashing the moment I would scroll the table. I had to add line tableData.retain after table initialization in viewDidLoad. I am not sure if this will cause any memleaks (new to iOS programming)

    - (void)viewDidLoad

    {

    [super viewDidLoad];

    // Initialize table data

    tableData = [NSArray arrayWithObjects:@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast", @"Hamburger", @"Ham and Egg Sandwich", @"Creme Brelee", @"White Chocolate Donut", @"Starbucks Coffee", @"Vegetable Curry", @"Instant Noodle with Egg", @"Noodle with BBQ Pork", @"Japanese Noodle with Pork", @"Green Tea", @"Thai Shrimp Cake", @"Angry Birds Cake", @"Ham and Cheese Panini", nil];

    tableData.retain;

    }

    • Daniel

      Thanks, also had this problem. I´m running xCode 3.2.6.

  • nad8e

    Enjoyed doing this project. However, I feel the tutorial dropped off with adding the same jpg to every line. I’ve tried and can not figure out, how do we make the image only show for a specific line and show another image on another line?

    How do we even go about looking up the appropriate way to add separate images to a table line?

  • Tiru

    Simple and complete. Thank you.
    I tried to use StoryBoard. Removed existing view and added Table view. But system is not identifying that UI.

    Am i missing any step.

    Thank you in Advance.

  • Vishal Raval

    Nice Job Sirji………..it is very usefull for me…….
    Thank you………

  • John

    I am having bit of trouble trying to make the images to show up on every row. I am using Xcode 4.6.1 version. Does anyone have an idea how I can fix it?

  • http://www.facebook.com/pattyla.patty.7 Pattyla Patty

    A great tutorial, tks!

    To share debug experience: File’s owner & View, Table View & dataSource delegate , the connections should be carefully in .xib

  • Matt

    I’m a bit confused as to why you spend ages explaining what an array is (something quite simple) and then just breeze over “Next, we implement the other required methods.” with absolutely no explanation!

    • http://www.simonblog.com Simon Ng

      The tutorial is written for beginner without programming background. That’s why we elaborate what an array is. For “other required methods”, you can find the explanation in “UITableViewDelegate and UITableViewDataSource” section.

  • http://twitter.com/neverbendeasy Erin Parker

    Thanks so much. This was simple, easy to follow, and well explained.

  • Pingback: Create a Simple Table View App – Prof. Kim's Daily Life

  • Mikhael

    hi, can u explain about “Go back to the “SimpleTableViewController.xib”. Press and hold the Control key on your keyboard, select the Table View and drag to the “File’s Owner”. ” I’m new to Xcode and im using Xcode 4.6.1, there’s no File owner as u mention above. im so lost even im googling searching for where i can find the file owner.

  • Mikhael

    please somebody, where is “File’s Owner” in xcode 4.6.1?

  • kitti

    I got message below, when i try to slide iPhone:

    2013-04-16 22:10:21.256 SimpleTable[1167:f803] -[__NSCFString objectAtIndex:]: unrecognized selector sent to instance 0x6e27390

    2013-04-16 22:10:21.263 SimpleTable[1167:f803] *** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[__NSCFString objectAtIndex:]: unrecognized selector sent to instance 0x6e27390′

    *** First throw call stack:

    (0x13ca022 0x155bcd6 0x13cbcbd 0x1330ed0 0x1330cb2 0x2ac4 0xaec54 0xaf3ce 0x9acbd 0xa96f1 0x52d42 0x13cbe42 0x1d82679 0x1d8c579 0x1d114f7 0x1d133f6 0x1dae1ce 0x1dae003 0x139e936 0x139e3d7 0×1301790 0x1300d84 0x1300c9b 0x12b37d8 0x12b388a 0×14626 0x1ff2 0x1f65)

    terminate called throwing an exception(lldb)

    Please help me.

  • Nayyar Awan

    super tutorial and i have resolve my scrolling problem with this peace of code

    - (void)viewDidLoad

    {

    [super viewDidLoad];

    tableData = [NSArray arrayWithObjects:@"one", @"two", @"three", @"four", nil];

    tableData.retain;

    }

  • Matty Hunt

    OK, the tutorial is great and I’m following it well but the homework………. can someone be kind enough to give me the code for this? Thanks.

  • venki dasari

    Nicely done

  • shailesh

    Superb tutorial :) Thank you very much :)

  • khanhtungna

    Very simple. Thank so much.

  • Durai amuthan

    Nice…

  • Hafiz Badrie Lubis

    This tutorial really helped me. Thanks!

  • Sam

    Great tutorial… question though: how do you reload the table if the array changes?