ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Computer Programming Tutorials

How To Develop an iOS iPhone or iPad App using SQLite Data and an UITableView

Updated on January 31, 2017
klanguedoc profile image

Kevin is Software Developer with 20 years experience designing and building software applications including iOS and Android apps.

Learn how to build iOS SQLite database apps using Swift 3
Learn how to build iOS SQLite database apps using Swift 3 | Source

(c) 2012 kevin languedoc (klanguedoc)

iOS 10 makes displaying in a UITableView quick and easier with a lot less code than previous versions of the SDK. On the back side, SQLite is a great data persistence facility. Marrying the two together makes for a perfect combination for building IOS 5 apps.

This tutorial will demonstrate how to read data from a SQLite database, store that data in a NSMutableArray and display it in a UITableView.

Create a SQLite Database

For the sake of this tutorial, create a database with Firefox SQLite Manager addin. I am calling mine authorsDb.sqlite. I am going save it to a convenient location because I will need to copy it into the Xcode project through Xcode and Finder.

The database will have one table, books, with the following columns:

Create Books SQLite Table
Create Books SQLite Table

I add the following data to the table via the SQLite Firefox addin:

Add Book Data to Books Table in SQLite database
Add Book Data to Books Table in SQLite database

Once this task is complete, I will create the project and add the database.

Create a IOS Project

The first step is to create a Single View project that targets the iPhone. Make sure the storyboard option is enabled. Once the project is created and loaded delete the View Controller and in its place create a UITableViewController by dragging it onto the Storyboard canvas.

Select the Cell prototype and give it a unique Identifier in the Attributes Inspector

Add Identifier
Add Identifier

Expand the Frameworks folder and select the first framework. Right click on it and select “Show in Finder”. When Finders opens move up the enclosing folder until to get to the “usr” folder

usr Folder
usr Folder

Expand the "usr" folder and expand the lib folder. Scroll down to the, libsqlite3.0.dylib, library alias. Using the left mouse button, drag the alias to the root of the Frameworks folder. A Copy Page will display, make sure to uncheck the “Copy items into destination...” otherwise the alias will be copied into the Frameworks folder and will break your SQLite installation. By unchecking this option, while leaving the other checked, you are adding a reference only.

Copy Reference ONLY
Copy Reference ONLY

Next right click on the file in the FirstTableProject folder and select “Show in Finder”, navigate to the location where the authorsDb.sqlite file was saved. Repeat the same operation as before, but this time leave the copy option checked because we need to have Xcode copy the database file into the project.

Add SQLite database file to project
Add SQLite database file to project

Now that the database is setup, I am going to create a UITableViewController in the next step.

Create the AuthorVC UITableViewController

Create the AuthorVC UITableViewController by selecting Add new File in the menu. Select the UIViewController under the Cocoa Touch node. On the next page enter the AuthorVC name and change the subclass to UITableViewController

Add UITableViewControlelr
Add UITableViewControlelr
Name UITableViewController
Name UITableViewController

Make sure the iPad option is not selected.

Once the authorVC class is created, open the Storyboard and select the UITableView and add the class to he Custom Class field in the Attributes Inspector.

Add Custom UITableView class
Add Custom UITableView class

Next repeat the same operation in the following task. We will come back to this class in a moment in regards to creating a Objective-C class only.

Create Author Class

To create the Author class, repeat the same steps as before but choose the Objective-C class template instead. On the second page, enter the Author class name, the sub class must be NSObject

Add three instance variables like the screenshot below:

Author Header
Author Header

and implement them in the implementation file author.m

Author Implementation
Author Implementation

Implement AuthorVC

The step is the heart of the tutorial, adding data to the UITableView. Open the header file and import the sqlite3.h header file and declare a sqlite3 variable. Also declare a NSMutableArray instance variable.

Create a method, authorList with a NSMutableArray return type

AuthorVC Header
AuthorVC Header

Save the file and open the AuthorVC implementation file.

The first thing to do in the implementation file is add the sqlite3 library and author.h libs in the import section and implement the “theauthors” NSMutableArray using the @synthesize directive.

AuthorVC Implementation - imports
AuthorVC Implementation - imports

Two required UITableView methods must be imlemented are

  • numberOfSectionsInTableView
  • numberOfRowsInSection


The first one defines the number of sections and the second defines the number of rows per section. This is usually the count of the Array that is being used to populate the UITableView.

AuthorVC Implementation - Required Methods
AuthorVC Implementation - Required Methods

Next, implement the dataList NSMutableArray:

AuthorVC Implementation - dataList
AuthorVC Implementation - dataList

The method first defines the “theauthors” NSMutableArray. Next a NSFileManager object is defined, followed by a NSString instance variable for the db path. The code continues by checking to make sure the database file is indeed in the Resource path and attempts to open it. If all goes well, a query string of char is define and initialized with the query string.

Next a sqlite3_statement is defined and finally the sqlite3_prepare is called, passing in all the variables. If the statement is ok and successfully executed, an Author object is created and initialized. The next step will populate the “theauthors” NSMutableArray using a while expression to step through the rows with command sqlite3_step and adding the row data to the author properties. Make sure to add the author object to the array at the end otherwise the table will be empty.

Configure UITableViewCell

A couple of steps to complete this tutorial. Configure the UITableViewCell with the method, cellForRowAtIndexPath. First change the value of the “CellIdentifier” to the name you gave the Cell prototype.

Next define an int variable for the rowIndex which will be used to extract the corresponding value from the “theauthors” NSMutableArray. Define a new Author object and assign the author object at the rowIndex in the NSMutableArray.

Complete the method by adding the values to the cell.textLabel and cell.textDescription properties. That’s it.

AuthorVC Implementation - Configure Cell
AuthorVC Implementation - Configure Cell

ViewDidLoad

One final step is to call the dataList NSMutableArray method when the UITableViewController loads in the viewDidLoad method:

ViewDidLoad
ViewDidLoad

In Summary

UITableView offers some very powerful features to organize and display, which were out of the scope of this tutorial. SQLite and UITableView are both easy to work with for storing data and displaying it.

For more tutorials on SQLite programming with iOS for iPad or iPhone Apps check out the tutorials:

How to Add CRUD (Insert, Update, Delete) to iPad or iPhone Apps

How to create a CRUD App including Inputted (Read & Write) data in a Table View Controller and a Detail View Controller


Author.h

//
//  Author.h
//  FirstTableProject
//
//  Created by Kevin Languedoc on 12/5/11.
//  Copyright (c) 2011 kCodebook. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Author : NSObject{
    NSString *name;
    NSString *title;
    NSString *genre;
}

@property(nonatomic,copy) NSString *name;
@property(nonatomic,copy) NSString *title;
@property(nonatomic,copy) NSString *genre;

@end

Author.m

//
//  Author.m
//  FirstTableProject
//
//  Created by Kevin Languedoc on 12/5/11.
//  Copyright (c) 2011 kCodebook. All rights reserved.
//

#import "Author.h"

@implementation Author
@synthesize name;
@synthesize title;
@synthesize genre;

@end

AuthorVC.h

//
//  AuthorVC.h
//  FirstTableProject
//
//  Created by Kevin Languedoc on 12/5/11.
//  Copyright (c) 2011 kCodebook. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <sqlite3.h>

@interface AuthorVC : UITableViewController{
    NSMutableArray *theauthors;
    sqlite3 * db;

}
@property(nonatomic,retain) NSMutableArray *theauthors;

-(NSMutableArray *) authorList;
@end

AuthorVC.m

//
//  AuthorVC.m
//  FirstTableProject
//
//  Created by Kevin Languedoc on 12/5/11.
//  Copyright (c) 2011 kCodebook. All rights reserved.
//

#import "AuthorVC.h"
#import "Author.h"
#import <sqlite3.h>


@implementation AuthorVC
@synthesize theauthors;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [self authorList];
    [super viewDidLoad];

   }

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
    return [self.theauthors count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"AuthorsCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    int rowCount = indexPath.row;

    Author *author = [self.theauthors objectAtIndex:rowCount];
	cell.textLabel.text = author.name;
	cell.detailTextLabel.text = author.title;

    
    return cell;
}


-(NSMutableArray *) authorList{
    theauthors = [[NSMutableArray alloc] initWithCapacity:10];
    @try {
        NSFileManager *fileMgr = [NSFileManager defaultManager];
        NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"AuthorsDb.sqlite"];
        BOOL success = [fileMgr fileExistsAtPath:dbPath];
        if(!success)
        {
            NSLog(@"Cannot locate database file '%@'.", dbPath);
        }
        if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
        {
            NSLog(@"An error has occured: %@", sqlite3_errmsg(db));
            
        }
        
        
        const char *sql = "SELECT * FROM  books";
        sqlite3_stmt *sqlStatement;
        if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
        {
            NSLog(@"Problem with prepare statement:  %@", sqlite3_errmsg(db));
        }else{
          
            while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
                  Author * author = [[Author alloc] init];
                author.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
                author.title = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
                author.genre = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 3)];
                [theauthors addObject:author];
            }
        }
    }
    @catch (NSException *exception) {
        NSLog(@"Problem with prepare statement:  %@", sqlite3_errmsg(db));
    }
    @finally {
	sqlite3_finalize(sqlStatement);
        sqlite3_close(db);

        return theauthors;
    }
}


@end

Running App

Here is the final result, the application running in the simulator.

The Application Running in the Simulator
The Application Running in the Simulator

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      Keyshawn 2 months ago

      How would you do this to display data in a nstableview with multiple columns

    • klanguedoc profile image
      Author

      Kevin Languedoc 12 months ago from Canada

      Hi Sarascydia,

      Good question. I don't know. I never tried it. Let me know how it goes. I promise to respond in a more timely manner :)

    • sarascydia profile image

      Sara Allen 15 months ago from United States

      Does this work for iOS jailbreaking? They have released jailbreak tool for iOS 9.3.5. How is this possible? https://www.instantjb.com

    • klanguedoc profile image
      Author

      Kevin Languedoc 2 years ago from Canada

      Thanks

      The source code is available at

      iosdev101.com/downloads

    • profile image

      Serkan 2 years ago

      Hey thanks for good tutorial. Can you send the source code?

      srkanerkan at gmail dot com

    • klanguedoc profile image
      Author

      Kevin Languedoc 3 years ago from Canada

      Sorry for the late response...

      The %@ is for string data type and %s is for char data type. sqlite3_errmsg return value is in char so you need to specify %s

    • shahpratik profile image

      Pratik Shah 3 years ago from Mumbai

      Hi Kevin,

      I am getting error on these two lines...

      "NSLog(@"An error has occurred: %@", sqlite3_errmsg(db));"

      and

      NSLog(@"Problem with prepare statement: %@", sqlite3_errmsg(db));

      The error says " Format specifies type 'id' but the argument has type 'const char *'.

      Fix-it Replace "%@" with "%s"

      Any idea what's going on?

      Thanks!

    • klanguedoc profile image
      Author

      Kevin Languedoc 3 years ago from Canada

      thanks, I appreciate the feedback

    • profile image

      John 3 years ago

      Thankyou very much for this tutorial. Extremely helpful!

    • klanguedoc profile image
      Author

      Kevin Languedoc 3 years ago from Canada

      Jay,

      That is a simple insert. I have written a tutorial on that in this collection. When the button is pressed IBAction, just capture the value in do an insert.

      Austin,

      Thanks for the praise. I really appreciate the feedback. I am working on a book. Hope to have it out in a few months.

      Claus,

      Your table doesn't have any columns or you are trying to access a column that doesn't exists. Remember that SQLite is a C based API and so the columns is a 0 based array

      Nam,

      There doesn't seem to be any changes to the SQLite API for iOS 7

    • profile image

      Moi_vingttrois 3 years ago

      Hi there, I have a question, I am trying to make my first app, I wish to have four maybe five screens and I wish to use a database, like you did in this, I thought I understood the tutorials well but obviously not, there is nothing showing up when I run the file but an empty table. I have spent so long on this I am losing my mind! Im sure it's something silly that I have over looked. Please any help/suggestions would be greatly appreciated, I am trying to teach myself this stuff and Im afraid I am not getting very far with it.

      M

    • profile image

      Austin 3 years ago

      Hello Kevin,

      Just wanted to say this tutorial (with the added detailView example) was the most helpful tutorial I have found on the web. (I also own a very large book for learning iOS7 App Building) Your tutorial gives a great example on understanding TableView Navigation with using SQLite as the datasource. Thank you so much for providing the source code on your website.

    • profile image

      Claus Juhl 3 years ago

      Hi :)

      I get "Bind or column index out of range". Any idea of what to look for?

    • profile image

      nacm 3 years ago

      what are the changes for ios 7?

    • profile image

      MoNigeriaes 3 years ago

      Any follow-up on how to do a details page?!

      [detail view]

      (btw tutorial was wonderful -- I've tried many and this was the first that actually worked for me)

    • profile image

      Jay 4 years ago

      Hi Kevin,

      I was wondering if you could tell me how i would go about implementing an SQLite db with button presses. That saying, a screen opens with two/three/four buttons, you click one and it stores the information on the buttons into the db. Maybe then being able to flick to a screen that see's all stored instances of button presses. Just trying to create a question app using sqlite for my family and its going horrendously that's all!

    • klanguedoc profile image
      Author

      Kevin Languedoc 4 years ago from Canada

      The database is stored in the documents folder which is read/write by default

    • profile image

      Trit 4 years ago

      I mean, if I want to, for example, run my app on my iPhone, how can the database be accessed, if we are not creating any copy of it but only adding a reference?

    • profile image

      Trit 4 years ago

      I see, many thanks! But is the database actually stored on the device?

    • klanguedoc profile image
      Author

      Kevin Languedoc 4 years ago from Canada

      the database should be in the Resource folder (the main or root).You need to add the db to the project.

    • profile image

      Trit 4 years ago

      Hi! Thanks for your tutorial, it's very useful! I am not getting any compilation errors, but keep getting a "no such database" message. Where could the problem be? Are you saving a db anywhere on mac?

    • profile image

      Alina 4 years ago

      Great tutorial, many thanks!!!

      I also added detail view and everything works! I'm just happy! :)

    • klanguedoc profile image
      Author

      Kevin Languedoc 4 years ago from Canada

      Hi phabrisse

      option 1:

      ouble sum = 0.0;

      sum = sqlite3_column_double(sqlStatement, colNumber1)+ sqlite3_column_double(sqlStatement, colNumber2);

      option 2:

      NSNumber * sum = [NSNumber numberWithDouble:([sqlite3_column_double(sqlStatement, colNumber1)] + [sqlite3_column_double(sqlStatement, colNumber2)])];

      You might need to tweak a bit

      Kevin

    • klanguedoc profile image
      Author

      Kevin Languedoc 4 years ago from Canada

      Stan,

      To load data into the UITableView to need to define an NSArray or NSMutableArray. I never tried 10k rows. I guess this is a trial and error situation.

    • profile image

      Stan 4 years ago

      Hi klanguedoc

      I thank you for your feedback.. I was not talking about the performance of sqlite :) but about the fact to load 10k rows into an array for the UITableview management...

      Do you think (as Tom said -the first post-) it's "cool" to load all the rows into an array ?

      I read the barefeetware solution, but I have doubts about the performance too, cause he individually loads in the (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath method...

      What do you think?

    • profile image

      phabrissse 4 years ago

      HI,

      Thanks a lot for your great tutorial.

      I have question:

      I have two columns with decimal number declared as REAL in my database .

      I would like to know how to get the sum of these two columns (sum=column1+column2)?

      Thanks

    • klanguedoc profile image
      Author

      Kevin Languedoc 4 years ago from Canada

      Long

      You can download the code from www.iosdev101.com/downloads

      look for the MywineList.zip

      Stan,

      If you read the documentation on SQLite web site, there is a size limit (2 terabytes) but they don't recommend using SQLite for very data sets. It wasn't designed for type of use. Even the web site recommends a database server for large datasets. I have seen SQLite dbs at greater than 500mbs and they were running fine.

      Now 10k rows may or may may not use a lot of space, depending on the number of columns and data types and the stored content. Some thoughts on SQLite performance is to import large amounts of data as a single transaction (update indexes at the end). The columns in the where clauses should be in the same order as in the db.

      Have you considered mysql (embedded) as an alternative? If you see your database too large. Anyway, ios device has limited space, so you will need to keep this in mind, possibly having a backup strategy to lessen the number of rows...

      Hope this helps

      Kevin

    • profile image

      Stan 4 years ago

      Hi,

      Thanks for sharing this article.

      I've a little question about large datasets (10 000 rows)...

      What would be the best approach ?

      I read the method of Barefeetware (http://www.barefeetware.com/sqlite/iosxcode/?li)

      It seems cool.. but I don't know if the fact to perform a select record per record is good for performance...

      Thanks for you advices...

    • profile image

      Long 4 years ago

      Thank you!

      I want to download the source code on.

    • lorddraven2000 profile image

      Sam Little 4 years ago from Wheelwright KY

      Very nice tutorial and you explained it in a very easy to understand and navigate way. Thanks very much for sharing this.

    • klanguedoc profile image
      Author

      Kevin Languedoc 4 years ago from Canada

      Thanks Isuru for the kind words and compliments. I am truly glad that my tutorials have helped you. When I sent out to write these tutorials, I wanted to write tutorials that I wanted to read as a programmer.

    • profile image

      Isuru Nanayakkara 4 years ago

      First off, I cannot thank you enough for this awesome tutorial! I recently started iOS developing. I've been trying to write a small app that displays data from a DB in a Table view for the past couple of weeks following number of tutorials on the net but to no avail. Lots of them are out of date and others were filled with mistakes. I finally managed to accomplish it following your tutorial. Thank you very much! :)

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      thanks newTween

      john_peter, have you tried a different encoding like utf-16

    • profile image

      john_peter 5 years ago

      Hello!

      i created a table with korean and english word first as VARCHAR type and secondly as TEXT both are displaying strange characters for korean words even when i use utf8string or utf8char to convert those words...your help would really allow me to go forward :)

      i hope to read you soon!

    • profile image

      newTween 5 years ago

      Great tutorial m8.

      Thx for your efford.

    • Vetranks profile image

      Vetranks 5 years ago from Shinjuku-ku, Tokyo, Japan

      Hi Kevin no problem and thanks again

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      Hi

      I didn't have time yet, but I will look at it and try to help you out.

      Kevin

    • Vetranks profile image

      Vetranks 5 years ago from Shinjuku-ku, Tokyo, Japan

      Hi kevin have you see my project?

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      ok Vetranks, but it might take a couple of days :)

    • Vetranks profile image

      Vetranks 5 years ago from Shinjuku-ku, Tokyo, Japan

      Well, now it's all just not me populates the table with data from the database, I send you the project if that's not a problem and an eye for the pleasure :-)

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      Your problem is that the navigation controller is not receiving right the selector. It is better to build from scratch, testing as you go and add parts of my tutorial to your new project. If this doesn't work you can send me your project, except I am very busy with dev projects and take me awhile to look at.

    • Vetranks profile image

      Vetranks 5 years ago from Shinjuku-ku, Tokyo, Japan

      Hello, here is what I did, I added viewcontroller like home, with button is connected to a navigationController with relative tableview populated with static data, a cell is in turn linked to your tutorial, and here the error occurs, the return from your tutorial to the first table does not occur naturally and NEAC if I put a button if you want I send you the project via e-mail, however, the error is SIGABRT

      16/10/2012 09:52:46.227 FirstTableProject [2578:11303] - [UITableViewController setAuthor:]: unrecognized selector sent to instance 0x71a5890

      16/10/2012 09:52:46.300 FirstTableProject [2578:11303] *** Terminating app to uncaught exception two 'NSInvalidArgumentException', reason: '- [UITableViewController setAuthor:]: unrecognized selector sent to instance 0x71a5890'

      *** First throw call stack:

      (0x1d66012 0x11a3e7e 0x1df14bd 0x1d55bbc 0x1d5594e 0x375f 0x460ac7 0x460b54 0x11b7705 0x1c920 0x258b24 0x11b7705 0x1c920 0x1c8b8 0xdd671 0xddbcf 0xdcd38 0x4c33f 0x4c552 0x2a3aa 0x1bcf8 0x1cc1df9 0x1cc1ad0 0x1cdbbf5 0x1cdb962 0x1d0cbb6 0x1d0bf44 0x1d0be1b 0x1cc07e3 0x1cc0668 0x1965c 0x229d 0x21c5)

      libc + + abi.dylib: terminate called throwing an exception

    • Vetranks profile image

      Vetranks 5 years ago from Shinjuku-ku, Tokyo, Japan

      no, i have added a viewcontroller whitout the navigation

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      Did you add a Navigator View Controller? What is the error in the SIGABRT?

    • Vetranks profile image

      Vetranks 5 years ago from Shinjuku-ku, Tokyo, Japan

      Sorry, but we do not understand anything anymore :-(, then I put in a home page with the storyboard type UIViewController which then put a menu, a page I linked the table the tutorial, if I click on the simulator I log in in the table and then to see the details, but once I get back from the details to the table I can not go back to the home page, why? I have added a button in the table but I get SIGABRT error and can not figure out where the wrong.

      thanks

    • Vetranks profile image

      Vetranks 5 years ago from Shinjuku-ku, Tokyo, Japan

      well and how do I go back to the first page and a viewcontroller?

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      You're welcome Stefano.

      the back button is provided for free when you add the Navigation controller. you don't need to manually add it. You re getting this error because the object represented by the sender argument is not the one the navigation controller is looking for. Remove the custom back button.

    • Vetranks profile image

      Vetranks 5 years ago from Shinjuku-ku, Tokyo, Japan

      Thank you Kevin and I wanted to ask why if I put a button to return to the tableview to a hypothetical homepage inserted using storyboards me error SIGABRT "10/15/2012 15:46:01.866 FirstTableProject [591:11303] - [UIViewController setAuthor: ]: unrecognized selector sent to instance 0x75688d0

      10/15/2012 15:46:01.868 FirstTableProject [591:11303] *** Terminating app to uncaught exception two 'NSInvalidArgumentException', reason: '- [UIViewController setAuthor:]: unrecognized selector sent to instance 0x75688d0'

      *** First throw call stack:

      (0x1d66012 0x11a3e7e 0x1df14bd 0x1d55bbc 0x1d5594e 0x397f 0x460ac7 0x460b54 0x11b7705 0x1c920 0x1c8b8 0xdd671 0xddbcf 0xdcd38 0x4c33f 0x4c552 0x2a3aa 0x1bcf8 0x1cc1df9 0x1cc1ad0 0x1cdbbf5 0x1cdb962 0x1d0cbb6 0x1d0bf44 0x1d0be1b 0x1cc07e3 0x1cc0668 0x1965c 0x248d 0x23b5)

      libc + + abi.dylib: terminate called throwing an exception

      (lldb) "

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      Convert your table to a static table in the Attribute Inspector

      vetranks

      I have added the detail view controller to the project. The new source code is on my web site at

      https://sites.google.com/site/ios101dev/downloads

      The new project file is :

      FirstTableProject 2.zip

      I will update the tutorial later this week.

    • profile image

      Wayne 5 years ago

      I have exactly the same as you, but I want sections and you don't have it

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      Maybe I don't understand, are you referring to a static table? Otherwise you set the number of sections you want and in the - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath to specify the information you want to display in a section or group of data.

    • profile image

      Wayne 5 years ago

      Thank you for your reaction, I know that I have to do that. But I don't know what to do then, I know I have to use this :

      - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

      {

      }

      - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

      {

      }

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

      {

      return [self.theauthor count];

      }

      But what now? I hope you can help me a little

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      You can define sections in the TableView either through the Attributes inspector in Xcode or through the - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView method

    • profile image

      Wayne 5 years ago

      Hello, at first thank you for your tutorial it is very nice.

      But i would like sections in my TableView but i don't know how I have to do that can you help me please

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      I will update tutorial to include detail view controller functionality

    • Vetranks profile image

      Vetranks 5 years ago from Shinjuku-ku, Tokyo, Japan

      thanks Kevin fine, but i can't understand how i can have to change in

      - (void)viewDidUnload

      {

      [self setTreeInfo:nil];

      [self setTreePicture:nil];

      [super viewDidUnload];

      // Release any retained subviews of the main view.

      // e.g. self.myOutlet = nil;

      }

      - (void)viewWillAppear:(BOOL)animated

      {

      [super viewWillAppear:animated];

      // treeData = [[SampleData alloc] init];

      treeData = (SampleData *)self.treeData;

      self.treeInfo.text = treeData.treeDescription;

      self.treePicture.image = treeData.treePicture;

      }

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      Please review this tutorial. It does exactly this

      https://turbofuture.com/misc/iOS-How-To-Display-De...

    • Vetranks profile image

      Vetranks 5 years ago from Shinjuku-ku, Tokyo, Japan

      Hello guys I wanted to ask one last thing, how can I create a detail page of the authors of this project?

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      you got it!

    • profile image

      MissingHiker 5 years ago

      OK! I think I see! So... the array is actually a list of memory locations? And, if you don't create a new instance of the variable each time you add to the array, then each time you add to the array, you're just adding the same memory location again and again, and whatever was the last string to be stored in that memory location will appear in the array over and over?

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      When looping through the array, at first the I had set the new author instance outside of the array, so any new values that were set to the author weren't being added to the array. This is because the new values being set to the author weren't assigned to the same object, or pointer in memory so the same values were being displayed repeatedly. To add multiple items of author to the array, you must set a new instance of the author or other class in the array (address in memory), then add this new object to the array and also set that object to nil (preferably) before starting a new cycle.

      In other words, the object that is set outside the array is pointing an address that is different and you can't re-assign new values to the same address.

    • profile image

      MissingHiker 5 years ago

      I have one question about something that was solved some time ago but I was wondering if someone could help me understand why it works.

      The problem that was being discussed was that when the table was displayed, every item in the array was exactly the same. The solution was to reinitialize the variable "author" before fetching the next set of data from the database and passing that data onto the array theAuthors. Here is part of the previous discussion -

      ----------------------------------------------------------------------

      Will 8 months ago

      This part of the code, I believe, is the problem:

      Author * author = [[Author alloc] init];

      while (sqlite3_step(sqlStatement)==SQLITE_ROW) {

      author.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];

      author.title = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];

      author.genre = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 3)];

      [theauthors addObject:author];

      }

      Every time an item is added to the array it overrides the others. Before the item is added I do an nslog to make sure that the object added is different (which it is), but if I do an nslog immediately after that while statement, I find all of the items in the array are now exactly the same.

      Will 8 months ago

      I found the problem:

      Author * author = [[Author alloc] init];

      should be inside of that while loop. Put it inside and everything works fine

      -----------------------------------------------------------------

      I don't understand why this works, though. And I am intently curious... if we pass through the while loop, get a set of data (author, title, genre), and put it in the array called theauthors, then go thru the while loop again and get the next set of data, and add that next object to the array, how does that change the first object we already put in the array? And how is it that creating a new instance of the author variable is able to cure that?

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      Sandra & Betti,

      First let me apologize for not responding sooner, your comments didn't show up in my notifications. You want to show your images and information in a detailviewcontroller, please look at these tutorials:

      https://hubpages.com/technology/iOS-5-How-To-Displ...

      This shows how to send data to a view controller. For an UIImage, you just send NSData then use initWithData of the NSData class.

      Here is another example:

      https://turbofuture.com/misc/iOS-How-To-Display-De...

      If I don't respond within 24 hours in the future, send me an e-mail :

      kevinlanguedoc[at]gmail[dot]com

      :)

      MissingHiker,

      Thanks for the great feedback. I never of that problem before but thanks for the contribution. Maybe another developer may have experienced the same issue.

    • profile image

      MissingHiker 5 years ago

      If this helps anyone who's also been getting errors... I was getting errors as well so I decided to go to Finder and look at my projects folder to see what was in there and look myself at the db file my app was reading.

      I found that XCode, for whatever bizarre reason, was making a totally blank, empty copy of my database file, then trying to read that. It attaches (projectname.app) to the beginning of the name of your database file in the project folder, and then reads that version. So mine was, I think, "FirstTableProject.appAuthorsDB.sqlite" (or something, you get the idea). So, I copied my copy of the database file, which I knew was good, to the project folder, renamed it XCode's long name, and then I was able to get it to work. That's pretty convoluted, I hope it makes sense.

      Thank you so much for the tutorial, yours is the first time I've found an explanation of SQlite concepts I've been able to understand and I've looked at many! Looking forward to reading more of your stuff!

    • profile image

      Sandra 5 years ago

      Hi Kevin,

      we have tried this:

      - (void)viewWillAppear:(BOOL)animated

      {

      [super viewWillAppear:animated];

      Author *dbconnect = [[Author alloc] init];

      self.recipeNameNewLabel.text = dbconnect.authorName;

      }

      or the same :

      - (void)viewDidLoad

      {

      Author *dbconnect = [[Author alloc] init];

      self.recipeNameNewLabel.text = dbconnect.authorName;

      }

      The result is the Label is always empty :-(

      We hope you can help us to solve our problem :-)

      That would be great.

      We are sitting here since a week and think about this. But we can't find a solution.

      Regards

      Sandra & Betti

    • profile image

      Sandra 5 years ago

      I take a look to the other tutorials, but I need an example for a better understandig ... I am a little bit confused know ...

      It will be very nice if you can help us with an code example ...

      We are two absolute beginners in IOS Programming

      Cheers

    • profile image

      Sandra 5 years ago

      Hi,

      should I use ...

      - (void)viewDidLoad

      or

      - (void)viewWillAppear:(BOOL)animated

      Regards Sandra

    • profile image

      Sandra 5 years ago

      Hi Kevin,

      thank you so much for your quick answer.

      My problem is I don't know what to do in DetailViewController.m

      Before I used a Property List and wrote in the Implementation file something like this:

      - (void)viewDidLoad

      {

      [super viewDidLoad];

      self.rezeptbild.image = [UIImage imageNamed:[self.recipesDictionary objectForKey:@"bild"]];

      self.rezeptname.text = [self.recipesDictionary objectForKey:@"name"];

      But I don't know how to do this with SQLite ...

      I hope you understand what mean ... and you can help me... :-)

      Cheers Betti

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      Hi Sandra,

      Have you look a this tutorial:

      https://hubpages.com/technology/IOS-5-Tutorial-on-...

      basically you have to pass the data to an id object and dereference it in the object will display the value. Your code looks fine and should work.

      Here is another technique

      https://turbofuture.com/misc/iOS-How-To-Display-De...

    • profile image

      Sandra 5 years ago

      Sorry I see mistake in my code I have written...

      Now it is correct for a better understanding ....

      Sandra 4 minutes ago

      Hi Kevin,

      I try to set up a DetailViewController.

      I do a segue:

      - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

      { if ([segue.identifier isEqualToString:@"showDetail"]) {

      DetailViewController *dvc = segue.destinationViewController;

      dvc.theautors = [self.authorList objectAtIndex:[self.tableView indexPathForSelectedRow].row];}

      }

      In the DetailView header file I do this:

      #import -UIKit/UIKit.h-

      @interface DetailViewController : UIViewController

      @property(nonatomic,retain) NSMutableArray *theauthors;

      @property (weak, nonatomic) IBOutlet UILabel *recipeNameNewLabel;

      @end

      Is this correct or have I forgotten something in the header file?

      And I don't know what I should do in the Implementation file to show the text in my UIlabel?

      Can you give me an code example by using your tutorial, please.

      Cheers Sandra

    • profile image

      Sandra 5 years ago

      Hi Kevin,

      I try to set up a DetailViewController.

      I do a segue:

      - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

      { if ([segue.identifier isEqualToString:@"showDetail"]) {

      DetailViewController *dvc = segue.destinationViewController;

      dvc.theRecipes = [self.recipeList objectAtIndex:[self.tableView indexPathForSelectedRow].row];}

      }

      In the DetailView header file I do this:

      #import -UIKit/UIKit.h-

      @interface DetailViewController : UIViewController

      @property(nonatomic,retain) NSMutableArray *theauthors;

      @property (weak, nonatomic) IBOutlet UILabel *recipeNameNewLabel;

      @end

      Is this correct or have I forgotten something in the header file?

      And I don't know what I should do in the Implementation file to show the text in my UIlabel?

      Can you give me an code example by using your tutorial, please.

      Cheers Sandra

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      Great I am happy you able to resolve the issue.

    • profile image

      Luis 5 years ago

      Hi again, finally i figured it out. I have just selected the database .sql file in the X-code project, and in the File Inspector, I check the Target Membership. I seems that when i import the .sql file i hadn't got this option checked, and the app seems becoming crazy about the Path. Thanks

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      Is the database open? The error message indicates that one of your variables or other objects, like the sqlite_statement or database is not properly set, meaning that it is null (nil). Also if you are writing to the database, it must be in the documents directory. If your code moves the database file into the documents directory, make sure that you are accessing the database in the right place, meaning that if you open the database in the resource folder but your query is trying to access database in the documents directory, one of them won't be open.

    • profile image

      Luis 5 years ago

      Hi again, yes i have changed the database filename in the code to correspond with the physical database. I have tried 4 times and no solution. And i created the db with the SQLite manager, with a table with 4 fields. I have also added some data. More ideas??? Thanks in advance

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      did you change the database filename in the code to correspond with the physical database filename. Also is the db object properly created and initialized. the EXC_BAD_ACCESS error usually means a null pointer exception somewhere, so some object is null.

    • profile image

      Luis 5 years ago

      Hi, great tutorial. I follow the steps and I complete it, but when I finished i get the EXC_BAD_ACCESS error when it tries to execute the statement. I fixed it, recreating the database as another user asked in this forum.

      Now, I am trying to create my own app following that example, and i just change the field names in the database and translating the name of the variables and this stuff into spanish but i have the same error again, and now i can't fix it recreating the database. I also changed the "*" for the table fields. What can be the problem?? Thanks in advance

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      yes of course, but I have to go out. i will check later tonight.

    • profile image

      afridikhalid 5 years ago

      i am copying the same file but still its not working i have sent you the project can you please check what's the problem?

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      afridikhalid, your version looks fine. What was the problem with my version. I have used it several times as a template for several projects.

      Also make sure the filename you use for your database is the same name you put in the code, otherwise you will get a statement error.

      Vetranks

      Add a segue from the prototype cell to the detailViewController. In the tableviewcontroller implemented the prepareForSegue method. In this method add a new instance of the detailviewcontroller and the object or variable (declared in the header to be visible) .

    • profile image

      afridikhalid 5 years ago

      Thanks for sending the project i have already sent you a project that i had made it the same but its not working. also when i change the database in the project that you have sent it to me i will get the same problem i think there will be a problem with database i made another database and changed its contents but its not working

      thanks for your help

    • profile image

      afridikhalid 5 years ago

      I changed the code in the view did load and it's working fine now but i wanted to know if its practical or no will it give some problems in the future or its fine?

      - (void)viewDidLoad

      {

      [super viewDidLoad];

      theauthors = [[NSMutableArray alloc] init];

      NSString *dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"AuthorsDb.sqlite"];

      sqlite3 *database;

      if (sqlite3_open([dbPath UTF8String], &database) != SQLITE_OK) {

      sqlite3_close(database);

      NSAssert(0, @"failed to open database");

      }

      NSString *query = @"SELECT * FROM books";

      sqlite3_stmt *qStatment;

      if (sqlite3_prepare_v2(database, [query UTF8String], -1, &qStatment, nil) == SQLITE_OK) {

      while (sqlite3_step(qStatment) == SQLITE_ROW) {

      Author *author = [[Author alloc] init];

      author.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(qStatment, 1)];

      author.title = [NSString stringWithUTF8String:(char *) sqlite3_column_text(qStatment, 2)];

      author.genre = [NSString stringWithUTF8String:(char *) sqlite3_column_text(qStatment, 3)];

      [theauthors addObject:author];

      author = nil;

      }

      sqlite3_finalize(qStatment);

      }

      sqlite3_close(database);

      }

    • Vetranks profile image

      Vetranks 5 years ago from Shinjuku-ku, Tokyo, Japan

      Thank you very much, very interesting, but I can not figure out where I put IBOutlet for example to bring out the results in detailview

    • Vetranks profile image

      Vetranks 5 years ago from Shinjuku-ku, Tokyo, Japan

      Thank you very much, very interesting, but I can not figure out where I put IBOutlet for example to bring out the results in detailview

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      Sure no problem

    • profile image

      Zaheer 5 years ago

      Thanks for the tutorial Kevin. Can you please send the source code to zaheriley at gmail dot com? thanks in advance..

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

    • Vetranks profile image

      Vetranks 5 years ago from Shinjuku-ku, Tokyo, Japan

      sorry but I did a little bit of confusion, in practice I wish that clicking an item in the tableview I would open a new page with the details of the item, for example, if the database has the title and author usually wish I were out in other pages while in the tableview I just want the titles, I hope I was clear. thanks again

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      :), that was funny...

      Do you mean that when the detail view loads, you want a popover to appear: add the UIAlertView to the ViewDidAppear method and grab the data from the id pointer object. See the tutorial on how to get info from id object.

      Hope that is clear. If I am off track, please let me know how you want the popover to appear.

    • Vetranks profile image

      Vetranks 5 years ago from Shinjuku-ku, Tokyo, Japan

      Sorry my phone keyboard is not very god and I meant to detailview how can I do?

    • Vetranks profile image

      Vetranks 5 years ago from Shinjuku-ku, Tokyo, Japan

      fine thanks and for ma thriller detailview, how canzona i do?

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      Vetranks

      Yes you can use the UIAlertView to pass data to the message body. You might have to create an event or an event to call the UIAlertView. Also you will have to test to see how to manage the popover if you are also using a detail view.

      For the UIAlertView, you can check my tutorial

      https://hubpages.com/technology/iOS-5-How-To-Use-t...

      afridikhalid

      I will gladly send you the code.

    • profile image

      afridikhalid 5 years ago

      Thanks for all the help can you please send me a copy of this tutorial i have written all of them but still when i run the program it runs well but no data in the table view i get this message in debuger (2012-09-20 08:57:56.172 SqlUitableView[17924:c07] Problem with prepare statement: no such table: books)

      my email: afridikhalid@yahoo.com

      You are doing a good job helping people.

    • Vetranks profile image

      Vetranks 5 years ago from Shinjuku-ku, Tokyo, Japan

      or a detailview

    • Vetranks profile image

      Vetranks 5 years ago from Shinjuku-ku, Tokyo, Japan

      Hello, thanks for the tutorial, and I wanted to ask how you can do to open a pop up with the details of the database, when you click on the tableview.

      thanks

      PS: sorry for my english

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      Cool pinkhawk.

      Quite true psdwpintegration.

    • pinkhawk profile image

      pinkhawk 5 years ago from Pearl of the Orient

      wow! quite interesting... this triggers my curiosity...thank you! ^_^

    • psdwpintegration profile image

      WPintegration 5 years ago from Noida

      When we think about Smartphones and Tablets, Apple would be the first name come in mind!

    • klanguedoc profile image
      Author

      Kevin Languedoc 5 years ago from Canada

      Well I am glad. Please let me know if you more help. I am always willing to help if I can.

    • profile image

      JFE 5 years ago

      weird, now it's working no idea why . . . . .