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

(c) 2012 kevin languedoc (klanguedoc)

iOS 5 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

More by this Author


Comments 189 comments

BareFeetTom 4 years ago

Nice tutorial, but I think one major flaw in your approach. The whole idea of the UITableViewController (specifically, being a delegate for answering data requests from the UITableView) is to only load the data that you need to display.

SQLite is very good at retrieving one row at a time as needed, so the cellForRowAtIndexPath method should ask SQLite just for the row of data matching the requested indexPath (and only the needed columns).

By contrast, you are caching the entire SQLite table into an NSMutableArray (theauthors). If your SQLite table contains a thousand or a million rows but the UITableView is only displaying ten at a time, then this is a huge waste of time, memory and will probably crash your app.

You can see another approach here, though the tutorial itself is not as well put together as yours:

http://www.barefeetware.com/sqlite/iosxcode/?li

Tom


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Hi BareFeetTom, thanks for your comment.

I totally agree with you with what you are saying. The objective of the tutorial was to demonstrate to another developer how to load data from SQLite into an UITableView. The tutorial was in response to his request, so I obliged. Your tutorial is good.


David DelMonte 4 years ago

One area of using plain sqlite instead of core data intrigues me, as I am finding it quite difficult to search across core data entities. Whereas, using sqlite, I can write code to achieve searches across tables without too much bother.

Comments?


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

True, using good old SQL is fast and easy. I am a big fan but I also believe in the whole ORM ideology, which is what Core Data really is. I have used ORM technology on other platforms like Linq (.Net) and Hibernate (Java). So far both Linq and Core Data have an edge over Hibernate.

As for SQL, there will always be a place for both. You just got to know when you use which.


Mark 4 years ago

Thanks for doing this tutorial!! It's give me a better idea on how to implement the DB. I've followed through it all, but I seem to be getting one error for this line in the AuthoVC.m:

sqlite3_finalize(sqlStatement);

I get the error:

Use of undeclared indetifier 'sqlStatement', the above lines which reference it are fine though. Any ideas what might be wrong?

When I comment the line out I can build the project, but it only shows the last record in my DB table and it's shown three times.

Hope you can help.


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Move the code up to :

....

}

sqlite3_finalize(sqlStatement);

}

@catch (NSException *exception) {

NSLog(@"Problem with prepare statement

This is my mistake. Sorry for throwing a curve...


Mark 4 years ago

Yep that's better now, but I still only get the last row shown in my table and it shows three times, have I done something wrong?


Will 4 years ago

Any idea on why it won't let me set the UITableView to the custom class of my VC?

Thanks


Will 4 years ago

Never mind about connecting the VC. I am now having the same problem as Mark.


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Check your array elements (index) at the start of the method, does your array list the proper items, or does the array list all three last items?


Will 4 years 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 4 years ago

I found the problem:

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

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


Mark 4 years ago

Will,

Move:

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

into the while loop.

Thanks for posting it helped me see it :)


Will 4 years ago

Team work!


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Great team work. Sorry I wasn't there to help. I had a dinner party. I am glad you figured it out.


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

I have updated the source code in the tutorial. Thanks.


Mark 4 years ago

Thanks again for doing the tutorial Kevin. I was looking at being able to create a detail view for when a row is selected. I've created a view controller for the view and called the identifier 'detail'.

I've tried to add the following in the authorvc.h under:didSelectRowAtIndexPath

DetailViewController *detail =[self.storyboard instantiateViewControllerWithIdentifier:@"detail"];

[self.navigationController pushViewController:detail animated:YES];

But when I click on a row in the simulator nothing happens, I've also tried creating a segue from the table to the detail view but still nothing. Do you have any ideas why the detail view isn't being pushed on? Thanks.


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Glad to see your app is moving along. To use instantiateViewControllerWithIdentifier, add after your code:

detail.TextViewObject= [self.ArrayObject objectAtIndex:index];

[self.navigationController pushViewController:detail animated:YES];

For segues, use something like:

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

{

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

[[segue destinationViewController] setDelegate:self];

}

}

Hope this helps. This is not tested and may require more tweaking.

Kevin


Amey 4 years ago

Nice tutorial Sir,

But I am facing one problem.

It is giving the last entry in my database as output. I rechecked the code but again the same thing.

Please Help..

Thanks.


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Please read the comment above. You need to move the Author * author = [[Author alloc] init]; into the loop. Please review my corrected source code. Hope this helps.


Mike 4 years ago

I can't display the detailTextLabel.text part on the table view. I have followed this exactly. Here is the code portion:

Korean *korean = [self.vocab objectAtIndex:rowCount];

cell.textLabel.text = korean.Korean;

cell.detailTextLabel.text = korean.Romanization;

cell.detailTextLabel.text = korean.English;

Am I missing something? Even when I remove one of those, I still get nothing.


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

You code looks fine. Are you getting sn error message? Is your cellIdentifier properly set? The string value must match exactly the one set in the cell prototype in the storyboard.


Mike 4 years ago

No error message, just not displaying the Romanization and English on the same line as the characters. I've set the cell identifier as VocabCell and declared the same in the UITableViewController. (I'm also doing this an a iPad app if that helps any).


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Mike, this is kind of hard to analyze without seeing your code, and i am not asking to post anything here, have you looked at table config; how many sections are configure and your groupings. Are these set to display all your data? Instead of loading your data form the db, have you tried just display static text in each of the fields in the cell?


kriszsomogyi profile image

kriszsomogyi 4 years ago from Ashgrove, QLD

Sorry if this sounds like a stupid question (as i'm only starting out in programming).

I've learnt a lot from your code, but when i try using a table where one of the fields/columns is mostly made of integers (postcodes), i can't seem get it to work.

i've declared the variable as an integer and a postcode and tried various ways of relabelling the field as a varchar but to no avail.

Any ideas how i could do this?

For example i can use

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

but not

NSInteger PostCode = sqlite3_column_int(sqlStatement, 3)

or

bar.PostCode = NSINTEGER_DEFINED (integerValue) sqlite3_column_int(sqlStatement, 3)


kriszsomogyi profile image

kriszsomogyi 4 years ago from Ashgrove, QLD

i tried another column with fresh numbers and worked out that the database that i'm working with had some data that was incompatible. I went through thousands of records and took out any special characters and filled out any null cells with a default values. I think i can figure out how to convert the string to integer with no real hassle, although i'm struggling with how i can leave in special characters (its gotta be there somewhere). Any help would be great


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

No question is stupid! This is one of the confusing areas of Objective-C; int and NSInteger are essentially two different data types. It's like saying NSInteger is int on steroids. NSInteger is 32/64 bits and int is 16 bits, so you try something like this:

int one = 5;

NSNumber * anotherone;

anotherone = [NSNumber numberWithInt:one];

NSLog(@"value of one: %@", anotherone);


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

I should clarify, NSInteger is a wrapper class of type long.


Renan 4 years ago

Hello, I'm trying to figure out how to make queries on my code, like you made "select * from books" but when I try select name from books for example it gives me GDB, any idea?

Thanks!


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Hi Renan Can you see an error message in the Console. This would help a lot in deciphering the issue. Of the top of my head, nothing comes to mind, except is your db object properly set and does the db open?


Renan 4 years ago

Yes, actually I didn't get any error, just GDB, nothing above it... Just copy your entire code and substitute this part SELECT * FROM books --- for this SELECT id FROM books

for example, if you have id on your table, I guess you'll have...and that's it, GDB


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

id may refer to the data type id in Objective-C. In a real app, the primary key column should be named something other than id. Try the other columns.


Mark 4 years ago

Sorry, sort of going off topic, I've been looking at using the master-detail app template for ipad which Apple supply, but I want to have multiple detail views. I've tried to find some tutorials which use this with storyboard, but I can't find much.

Do you know of any good tutorials which go through how to do this? Maybe could you look at doing something like this for a future tutorial or your book?


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

You would need to implement some logic in the tableView method that loads the data into the TableView, Either a switch or and If op.

or

implement the same logic in the prepareForSegue method which would take your cell title value and based on value would the appropriate segue and also transfer the data to the proper DetailViewController. I will post some code...


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Hi Renan,

Try something like this. It is not testing and may require some tweaking...

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

NSString * segueName = [[NSString alloc] init];

if(tableViewCell == @"value")

{

segueName = [segue identifier];

}

if ([segue.identifier isEqualToString:segueName ])

{

// Get the detail view controller.

PhraseDetailViewController* destVC =

(PhraseDetailViewController*)segue.destinationViewController;

// Find the correct dictionary from the documents array.

NSIndexPath *cellPath = [self.tableView indexPathForSelectedRow];

UITableViewCell *theCell = [self.tableView cellForRowAtIndexPath:cellPath];

// Assign the URL to the detail view controller and

// set the title of the view controller to the doc name.

destVC.detailItem = theCell.textLabel.text;

destVC.navigationItem.title = theCell.detailTextLabel.text;

else if([segue.identifier isEqualToString:@"AnotherSeqgue Value"])

{

....

}


Anil 4 years ago

Nice tutorial... It helped me a lot.


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Glad to hear Anil. Thanks for your kinds words


Mark 4 years ago

Hi Kevin,

I dropped you a mail, do you mind taking a look when you have a chance please?


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Sure, no problem


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Hi Mark

I checked my mail. The last e-mail from 02/29/2012 but there is no attachment. Can you resend please.

Thanks

Kevin


Mark 4 years ago

Hey Kevin,

I'm still stuck!! Can you see the last mail I sent? Really don't know what might be wrong!


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Sorry Mark. I had a tough week. I will check your code.


kriszsomogyi profile image

kriszsomogyi 4 years ago from Ashgrove, QLD

Thanx for your help, I found a way to do it using what you suggested, I have a monster of a switch variable loop combo that I need to work on now. Cheers


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Cool, I am glad I was able to help. It is so frustrating to bang our heads over a piece of code that won't do what we want.

K


manojglobal profile image

manojglobal 4 years ago from Kolkata

good tutorial...


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Thanks manojglobal


Ric 4 years ago

Hi Kevin,

Great tutorial. I have done it twice and am getting the same error message:

Its EXC_BAD_ACCESS(code=1 address=0x073206f76) and when I run the code it stops at the line NSLog() in the code below in the "-(NSMutableArray *) authorList" method in the "AuthorVC.m" file.

I'm assuming its finding the database, but having a problem with the Select statement? I have doublechecked and the database and table are both named the same as in the tutorial. Any ideas?

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));

thanks Kevin!

Ric


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Thanks for the feedback

Try replacing the "*" with the actual column names. The bad_access_exec usually means that an object is null. Otherwise the code looks fine.


Ric 4 years ago

Hi Kevin,

I figured it out, sort of. I just recreated the database and gave it a different name in the dbPath. I guess it was stuck on a different version of the database somewhere.

Anyhooo, great tutorial. thanks, ric


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

I am glad everything sorted itself out. Happy coding.


mikeydcarroll67 4 years ago

I have another question on this. (moved onto the next app), Would it be possible to increase this loading to load 25 to 100 at a time without crashing an app? If so, what would be a better way?


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Hi Mikey,

You want to load 25 to 100 from db or into table view. For a select, you could try top 25 or 100 , like select top(100) col from table. There shouldn't be any issues assigning an array to the data source, no matter what size within reason.


mikeydcarroll67 4 years ago

OK. I'll try it out and see if there are any issues with that.


Jakub 4 years ago

Hi, thank you for great tutorial! I have an appeal, I would really appreciate if somebody could spread this tableView tutorial with detailed viewController...for example by tapping on some row it will query to particural detail view with some more info coming from the same sqlite DB...Thank you very much for any advise or illustrative tutorial.

 It is a bit different task than developing the app withouth storyboard. Thanks again!!


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Sure I will glad to help. Once you know how, it is quite easy.


Jakub 4 years ago

To Klanguedoc, I'm really happy that you are going to help me :-) I'am quite curious about it! :-)

Thanks a lot!


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

I am nearly finished the code. i will write up the instructions later today


Betti 4 years ago

Hi, thanks for the Great tutorial. Everything works fine.

I have a question: "How can I add an image to the tableview?"

I hope you can give me some code. Thanks...


klanguedoc profile image

klanguedoc 4 years ago from Canada Author


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

thanks for the great feedback..

Please see the tutorial at URL below, but add use the cell.imageView.image to assign an UIImage resource to the cell.


Jakub 4 years ago

Wow! Thank you many times "klanguedoc". I am looking forwar to learn this piece of code :-) later today.


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

You are very welcome Jakub. i am glad you appreciate


ravinder 4 years ago

plz let me know how can i get all the values from the array into my another class

thank u...


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

You could use the count property of the array to loop through the array and assign the values using the objectAtIndex method even though this last method is in the NSArray class

note: the comment box doesn't allow less than or greater than signs, so replace the "less than" by the proper symbol.

for(int i=0; i less than nsmutablearray.count; i++)

{

yourClass * val = [[yourClass alloc] init];

val.something = [nsmutablearray objectAtIndex:i];

}

I didn't test this so some tweaking may be necessary.

Kevin


mikeydcarroll67 4 years ago

Any chance that you might be interested in doing something like this for core data?


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Sure Mike,

I will try to put something together over the weekend if I can move my current chapter along a bit. Actually I really like working with Core Data because I used hibernate on Java and Linq with C# a lot and Linq / C# is very similar to Core Data.


Adam 4 years ago

Hi Thanks for your grade tutorial

I have the same error here, I 'm really new and I have everything step by step as your tutorial

Its EXC_BAD_ACCESS(code=1 address=0x073206f76) and when I run the code it stops at the line NSLog() in the code below in the "-(NSMutableArray *) authorList" method in the "AuthorVC.m" file.

I don't know what should I replace here as you said

Try replacing the "*" with the actual column names. The bad_access_exec usually means that an object is null. Otherwise the code looks fine.

since everything for me is the same as your tutorial would you please let me know what should I write :)

Thanks in Advance


Adam 4 years ago

I forgot to say, Is it possible for you to put your actual project in your tutorials?


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Hi Adam,

Since the source code is already in the tutorial, if you send me an e-mail, I will be to send you the project code. Because there is no way to attach the project itself to this web site.


Adam 4 years ago

Hi Thanks for your care and reply, I don't have your email address here is mine

adam.f32f@yahoo.com

would you please send me this project and also How-To Display SQLite Data in a UITableView and DetailViewController project

Thank you so much


Bahadir 4 years ago

UITableViewController error:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UITableViewController loadView] loaded the "2-view-16" nib but didn't get a UITableView.'

Problem?


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Are you using a storyboard or nib file? did you add elements and IBOutlets or IBactions to the storyboard and then removed them? if so, the storyboard still has a reference in the XML. open the storyboard as source code and search for 2-view-16.


sunny 4 years ago

I have a problem here,, it keeps come out with EXC_BAD_ACCESS during this part of code...

const char *sql = "SELECT * FROM books";

sqlite3_stmt * sqlStatement;

if(sqlite3_prepare(db, sql, -1, &sqlStatement,NULL)!= SQLITE_OK)

{

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

}

is there any problem????


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

If you copy and paste the source code from above you shouldn't have any problems. Look at the AuthorVC.m source code. If you still have problems, make sure the sqlite libraries are well set and that your database is open in Resource directory. Your error message means that one of your objects is NULL or not properly instantiated.


Nina Vu 4 years ago

To solve an issue with detail information should use next initialization for cell:

if (cell == nil) {

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

}


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Thanks for the feedback


gonce007 profile image

gonce007 4 years ago

Hi klanguedoc,

Such nice tutorial on i Phone apps and really useful for those who like to develop apps for i phones.

Keep posting like this.I will be in touch.


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Thanks for the feedback. Ifyou would like to see a topic in particular, please let me know.


hhelen profile image

hhelen 4 years ago

What a nice tutorial. I love it when someone takes their time to write a good and insightful tutorial like you've done here.

Good man.


piyushpatil85 profile image

piyushpatil85 4 years ago from Pune

how to add integer value and image in table what is the query in objective C?


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Thanks hhelen. I like to write tuts as if I was the person reading them and I like to read tuts that walks through all the steps because the person reading may not a glue on hoe to proceed.

piyushpatil85, please check out my other tutorial, but basically, you need to use the blob data_bind in Sqlite and on the Objective-C side you need to convert the image (UIImage) to binary (NSData).

https://owlcation.com/stem/Tutorial-on-Creating-an...

http://hubpages.com/technology/iOS-5-How-To-Displa...

I write up a tutorial on this if you like....

kevin


Grace Whites profile image

Grace Whites 4 years ago from Manalapan, New Jersey, USA

This is an interesting one. You have made an effort to share this with us. Thanks for sharing. I have no really idea about how to use SQL. Im glad that you shared your ideas here.


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Thanks Grace. Programming is a lot like writing, you more or less start with a blank piece of paper and let your imagination guide you.


CoachDave48 4 years ago

Kevin,

I am very thankful for your tutorial. I am brand new to imac, xcode and iOS so I find your step by step instruction very helpful.

I keep getting the same problem mentioned several times before, "exc_bad_access (code 1). I have tried creating the query with * and with field names as noted above.

I also tried recreating the database as someone else had success with. No luck.

I am really frustrated and if you could point me in the right direction I would be very, very grateful.

Thanks

Dave


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Sorry to hear that you are having problems

Basically the exc bad access error is coming an object that is not properly initialized. I can send you the source code to the project to help you out. Either send me an e-mail or add your email address to the comments.

Hope this helps


Anjo Bacarisas II profile image

Anjo Bacarisas II 4 years ago from Cagayan de Oro, Philippines

thanks for this wonderful hub, very useful information.. like it so much :)


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

I am glad you like it. Do you develop iOS apps?


JFE 4 years ago

I have done this using the same names for everything and it keeps showing this error

Problem with prepare statement: no such table: books


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Hi JFE

did you name the table in SQLite Mgr "Books" or "Book". Is there a space after the table name?


JFE 4 years ago

the table name is "books" no spaces, I just checked.


JFE 4 years ago

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


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

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


psdwpintegration profile image

psdwpintegration 4 years ago from Noida

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


pinkhawk profile image

pinkhawk 4 years ago from Pearl of the Orient

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


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Cool pinkhawk.

Quite true psdwpintegration.


Vetranks profile image

Vetranks 4 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


Vetranks profile image

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

or a detailview


afridikhalid 4 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.


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

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

http://hubpages.com/technology/iOS-5-How-To-Use-th...

afridikhalid

I will gladly send you the code.


Vetranks profile image

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

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


Vetranks profile image

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

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


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

:), 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 4 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

klanguedoc 4 years ago from Canada Author


Zaheer 4 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

klanguedoc 4 years ago from Canada Author

Sure no problem


Vetranks profile image

Vetranks 4 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 4 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


afridikhalid 4 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);

}


afridikhalid 4 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


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

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) .


afridikhalid 4 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

klanguedoc 4 years ago from Canada Author

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


Luis 4 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

klanguedoc 4 years ago from Canada Author

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.


Luis 4 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

klanguedoc 4 years ago from Canada Author

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.


Luis 4 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

klanguedoc 4 years ago from Canada Author

Great I am happy you able to resolve the issue.


Sandra 4 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


Sandra 4 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


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Hi Sandra,

Have you look a this tutorial:

http://hubpages.com/technology/IOS-5-Tutorial-on-H...

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...


Sandra 4 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


Sandra 4 years ago

Hi,

should I use ...

- (void)viewDidLoad

or

- (void)viewWillAppear:(BOOL)animated

Regards Sandra


Sandra 4 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


Sandra 4 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


MissingHiker 4 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!


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

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:

http://hubpages.com/technology/iOS-5-How-To-Displa...

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.


MissingHiker 4 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

klanguedoc 4 years ago from Canada Author

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.


MissingHiker 4 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

klanguedoc 4 years ago from Canada Author

you got it!


Vetranks profile image

Vetranks 4 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

klanguedoc 4 years ago from Canada Author

Please review this tutorial. It does exactly this

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


Vetranks profile image

Vetranks 4 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

klanguedoc 4 years ago from Canada Author

I will update tutorial to include detail view controller functionality


Wayne 4 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

klanguedoc 4 years ago from Canada Author

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


Wayne 4 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

klanguedoc 4 years ago from Canada Author

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.


Wayne 4 years ago

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


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

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.


Vetranks profile image

Vetranks 4 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

klanguedoc 4 years ago from Canada Author

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 4 years ago from Shinjuku-ku, Tokyo, Japan

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


Vetranks profile image

Vetranks 4 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


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

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


Vetranks profile image

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

no, i have added a viewcontroller whitout the navigation


Vetranks profile image

Vetranks 4 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


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

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 4 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

klanguedoc 4 years ago from Canada Author

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


Vetranks profile image

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

Hi kevin have you see my project?


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Hi

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

Kevin


Vetranks profile image

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

Hi Kevin no problem and thanks again


newTween 4 years ago

Great tutorial m8.

Thx for your efford.


john_peter 4 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!


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

thanks newTween

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


Isuru Nanayakkara 3 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

klanguedoc 3 years ago from Canada Author

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.


lorddraven2000 profile image

lorddraven2000 3 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.


Long 3 years ago

Thank you!

I want to download the source code on.


Stan 3 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...


klanguedoc profile image

klanguedoc 3 years ago from Canada Author

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


phabrissse 3 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


Stan 3 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?


klanguedoc profile image

klanguedoc 3 years ago from Canada Author

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.


klanguedoc profile image

klanguedoc 3 years ago from Canada Author

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


Alina 3 years ago

Great tutorial, many thanks!!!

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


Trit 3 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?


klanguedoc profile image

klanguedoc 3 years ago from Canada Author

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


Trit 3 years ago

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


Trit 3 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?


klanguedoc profile image

klanguedoc 3 years ago from Canada Author

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


Jay 2 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!


MoNigeriaes 2 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)


nacm 2 years ago

what are the changes for ios 7?


Claus Juhl 2 years ago

Hi :)

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


Austin 2 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.


Moi_vingttrois 2 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


klanguedoc profile image

klanguedoc 2 years ago from Canada Author

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


John 2 years ago

Thankyou very much for this tutorial. Extremely helpful!


klanguedoc profile image

klanguedoc 2 years ago from Canada Author

thanks, I appreciate the feedback


shahpratik profile image

shahpratik 2 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

klanguedoc 2 years ago from Canada Author

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


Serkan 22 months ago

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

srkanerkan at gmail dot com


klanguedoc profile image

klanguedoc 22 months ago from Canada Author

Thanks

The source code is available at

iosdev101.com/downloads


sarascydia profile image

sarascydia 3 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

klanguedoc 3 days ago from Canada Author

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 :)

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working