iPhone Programming Tutorial – Creating a ToDo List Using SQLite Part 1

August 19th, 2008 Posted by: brandontreb - posted under:Tutorials

If you have been following my tutorials, you know that we have been working primarily with UITableViews.  This is mostly because SO many applications can be developed using this simple control.  This final UITableView tutorial will be taking all of the skills learned from previous tutorials, putting them all together, and adding SQLite to create a prioritized To-Do list.  I will also be showing you how to add multiple columns to your table cells and we will be exploring some of the other controls that the iPhone has to offer.  What good would the tutorials be if we didn’t use them to create something useful.

I will move a little faster in this tutorial while still explaining the new stuff in detail.  I will assume that you have completed the fruits tutorial and it’s prerequisites.

This tutorial will be a multipart series as it will be a little longer than my previous ones.  In this first tutorial, you will learn:

So let’s get started…

Open up X-Code and Select File->New Project… Select Navigation-Based Application and click Choose…

Name your project todo.  Now let’s create the todo database that we will be using.  Open up the Terminal application on your Mac.  This is located in Applications > Utilities.

If you have installed XCode, you should have mysqlite3 already on your computer.  To check this, type:

sqlite3 into the Terminal and sqlite3 should start. Type .quit to exit. If sqlite3 is not installed, install all of the XTools from your Mac Installation Disk.

Now that the terminal is open let’s create the database. This is done with the command:

sqlite3 todo.sqlite

SQLite3 will now start and load the todo.sqlite database.  By default the database is empty and contains no tables.  If you need a refresher on the basics of SQL databases Since our application is fairly simple, we only need to create one table.  We will create a table called todo by typing the following statement:


One thing to note here is the pk field.  It is the primary key of the table.  This adds functionality such that every time a row is added to the database, it auto-increments this field.  This will be a unique identifier to identify each row.  All of the other fields should be fairly self explanitory.

Now that our table has been created, let’s add some data.  We will eventually be adding todo items within our app, but for now we will add some defaults.  Type the following commands below.

INSERT INTO todo(text,priority,complete) VALUES('Take out the trash',3,0);
INSERT INTO todo(text,priority,complete) VALUES('Do Computer Science homework',1,0);
INSERT INTO todo(text,priority,complete) VALUES('Learn Objective C',1,0);
INSERT INTO todo(text,priority,complete) VALUES('DIGG this tutorial',2,0);

You can add as many todo items as you would like.  For this tutorial, make sure you enter a priority between 1 and 3 (You’ll see why later).  Now our database has been created and populated let’s exit out of SQLite3.  Do this by typing .quit.  Your terminal window should look something like this.

Now go back to XCode.  Do a Control-Click (right click) on the folder named Resources. Click Add -> Existing Files… and browse to your todo.sqlite file and click Add.  It will then prompt you with a screen like this.

Make sure you check the box that says Copy items into destination group’s folder (if needed). You should now see the todo.sqlite file inside of the resource folder.

Now that we have added the database, we need to load the Objective C libraries so we can use it.  Do a control-click (right click) on the Frameworks folder.  Click Add -> Existing Frameworks.  Now this part is a little strange.  It has been my experience that these libraries are not in the same place on all machines.  So in the search bar type in libsqlite3. The file we are looking for is called libsqlite3.0.dylib. This may pull up multiple files as OSX has it’s own versions of this file.  Just click on the largest of the files that show up and click Add. As you can see, mine is about 1.7 MB.

Now it should add the framework and your directory will look something like this:

We need to create an object to hold our todo information.  We will eventually be making an array of these objects to populate a UITableView.  Go ahead and click File -> New File… Select NSObject Subclass and click Next.

Name this object todo.m and check the box that says Also create “Todo.h” and click Finish.

Open up todo.h and add the following code.

We see some new things here…First, there is a variable of type sqlite3 called database.  This will be a reference to the applications database and will allow the todo object to communicate with it.  Make sure you add a #import<sqlite3.h> in your imports.

Next, we see a primary key.  Notice that in the property declaration it has the keywords assign and readonly.  This tells the compiler that this variable, once assiged, can not be changed again.  This is good since each todo will be uniquely identified by this variable.

Also, I have declared a method called initWithPrimaryKey.  This will be the contstructor for this object.  It takes an integer to assign as the primary key and an sqlite3 object to use as the database reference.

Let’s implement this method…Open up todo.m and add the following code.

There are quite a few new things that need to be explained here.  I will just go through it line by line.

static sqlite3_stmt *init_statement = nil

This will hold our initialize statement when retrieving todo data from the database.  This statement is static, meaning it is independent of any instance.  In other words, there will be only one of them no matter how many todo objects we create.  This statement will get compiled and allow us to do some neat things.  I’ll explain more  in a bit.

The next lines makes sure that the super class (NSObject) initilizes properly before we initilize a todo object.  We then set the local primary key and database objects to the parameters passed to the initWithPrimaryKey method.

Now some interesting stuff happens.  The next lines checks if our init_statment is null.  This will happen only once per launch of the application.  If it is null, we create a new string containing an SQL statement.  If you are familiar with SQL at all, this should look pretty familiar with one exception.  What is a question mark doing in there?  Well, I will tell you.  After the SQL statement gets compiled, we can bind a value to it that will eventually replace the question mark.  So this allows us to have 1 generic SQL statement, but bind different values to it to retrieve different results.  So the next line, you guessed it, prepares the statement and stores it in our init_statement.  The if statement just checks to see if this finished correctly and prints an error if there was a problem.

Moving on… The line sqlite3_bind_int simply replaces that question mark with the primary key of the current todo object, so what we end up with is statements like this:

SELECT text FROM todo WHERE pk = 1;
SELECT text FROM todo WHERE pk = 2;
SELECT text FROM todo WHERE pk = 3;
SELECT text FROM todo WHERE pk = n;

After that, the sqlite3_step(init_statement) method is called.  This method executes the SQL statement on the database.  It is contained inside of an if statement to make sure it executed properly.  Now we can finally access the todo data.  We see this line:

self.text = [NSString stringWithUTF8String:(char*) sqlite3_column_text(init_statement,0)];

Wow, that’s a mouthful… Let’s analyze it.  The sqlite3_column_text method tells SQL that we want to retrieve a string object from the database.  It has 2 parameters.  The first, is just a reference to the SQL statement that was used.  The second is the column number that we wish to get text from.  So in this case, we only have one column (SELECT text FROM…) so there is only 1 index and that’s the 0th index.  Next, the (char *) is just a cast to a string (might not be needed, but good practice).  And finally, we build an NSString object with the data returned so that we can assign self.text to it.

This is quite a bit to explain in just text.  If I have lost you, feel free to ask me questions in the comments.

We are done with the todo object for now…

Go ahead and open up todoAppDelegate.h and add the following code.

This should look a little familiar with the exception of a few lines.  Notice that I have created an NSMutableArray of todo objects.  This will be (like the fruit example) an array to hold our todo items.  We will eventually use this array to populate a UITableView.  The only new lines here are the import of sqlite3.h and the sqlite3 *database line. Now let’s open up todoAppDelegate.m and add some code.

One new thing we see here is a private interface.  We declared it here because it’s specific to this object so it does not need to be declared in the .h file.  The 2 functions we will implement are createEditableCopyOfDatabaseIfNeeded and initializeDatabase.  Much of the code for these has already been written for us inside of Apple’s SQLBooks tutorial.  I will going through this code and explaining it the best that I can. Add the following code.

What this method is essentially doing is copying the database from your project folder to the documents folder on your iPhone.  This will only happen once as it first checks if the database already exists in the documents folder.  I’m not going to go through this line by line as it is fairly self explanitory.  Apple does a great job of naming functions and variables so that we can understand what is going on.  If I get enough requests in the comments, I’ll do a line-by-line writup of this function.

The next function we will implement is initializeDatabase. Add the following code:

That’s a lot of text! Don’t worry it’s mostly comments.  Let’s analyze this code…Some of it is very similar to the fruits example.

The first line creates and initializes a NSMutableArray.  We then go on to set this array to our object’s todos array and release the temporary object.

The next 3 lines locate the database we created inside of the documents folder.  Following that, the sqlite3_open line open’s the database so we can access its data.  If the database opens correctly, we then proceed to retrieve todo items.  The first line:

const char *sql = "SELECT pk FROM todo";

is an SQL statement that we will use to get all of the primary keys from the database.  We then prepare the statement (as we did inside the todo.m file) only this time there is no “?” in the statement.  That is because there is not condition for retrieving the primary keys.  We are simply saying “give me all of the primary keys in the database”.

Now we see a while loop that is stepping through the SQL results.  Every time we call sqlite3_step, the next result gets retrieved.  The line:

int primaryKey = sqlite3_column_int(statement,0);

retrieves the primary key from each result.  This is very similar to retrieving the text in the todo.m class only  we use the sqlite3_column_int method instead of the sqlite3_column_text method.  This is done for obvious reasons.

After we have the primary key, we create a new Todo object and call the initWithPrimaryKey constructor that we created.  The primary key gets passed as well as a reference to the database.  This allows the Todo object to essentially “look itself up” in the database.  Finally, we add the newly created Todo object to our array of todos.

The last statement sqlite3_finalize clears the statement from memory and does some other cleanup.

The last part of this tutorial is calling these functions to create and initialize the database.  So add the following code to applicationDidFinishLaunching:

We are simply calling these functions.  You can now click Build and Go but your application won’t display anything!  You might be quite frustrated that you completed this portion of the tutorial and have yet to see anything.  Well, stay tuned! I will have the next portion of this tutorial up soon.

For you ambitious programmers you could move on.  If you notice, at this point we are in a similar situation as the fruit tutorial.  We have an Array of objects that will eventually populate a UITableView.

This tutorial will be a 4 part series and I will show you how to use a few more controls.  We will be adding, editing, and deleting todo items.  If you have any questions, please leave them in the comments.  Also, if you get lost you can download the sample code here

Happy iCoding!

  • shardayyy

    Nice tutorial, Are you planning to do something on Tab’s along with this todo list.

    Just like the IPod tabs (Songs | Playlist | Album | etc)

    Where each tab uses its own NIB/XIB file.


  • http://icodeblog.com Brandon

    Actually, I am considering it if there is enough interest.

    I was thinking of having 3 tabs: all todos, completed todos, and incomplete todos.

    Thanks for reading!

  • Thomas

    Interest ?! Lots from me at least !

  • textual

    i was building this very project for my own ‘learn as you go’ project
    very similar to this, it is based off of the sql lite tutorial on ADC

  • Phil

    great tutorial Brandon, i’ve created my database using a SQLite GUI application rather than through the terminal – i’ve ended up with a todo.rsd file rather than a todo.sql file will this still work ok?

    I would also like to see how to work with the tabs,so would be great if you could include it in this tutorial set as an example.

    One other point – could you include the source code for each part of the tutorial?


  • bobcubsfan

    Brandon, you have done it again. Thanks for “Part 1.” Although I am tempted to continue on before you post the remaining parts, I make so many typos, that I am willing to wait for you.

    Thanks again for your great teaching.

  • Nebkiwi

    able to do a navigation based application with a different nib for each item? little stuck on that and that would be a great help, left a post on forum as well if you want to help me on there.

  • Darryl

    Great tutorials, definite book material.

    The combination of type as I do, followed by explanations of what the code does suits the way I learn.

    I am trying to create a hybrid of your helloworld (without navigation controller) and the fruit example.

    Basically picking the “fruit” takes you to a view that has several textfields and a button instead of the single textview like in the original fruit example. The second view is the same for all “fruit”.

    you enter some numbers, press the button, some calcs are done and the results are placed in some other textfields.

    The problem I am having is filling out the input textfields. When I click on the textfields the keyboard comes up and I can enter the numbers but then the keyboard won’t go away. I have tried several combinations in interface builder of auto enter and showing the done key but nothing works. If I hard wire some numbers in the Viewdidload function, so I don’t have to invoke the keyboard, and press the button everything else works ok.

    I am thinking that it has something to do with the fact that the transition is a navigation controller and I need to do something else to release the keyboard or let that controller know about the keyboard.

    I have noticed in other examples that the navigation bar has separate edit or save buttons that you have to press before getting the keyboard and am wondering if I need to take another step.

    If all of this makes any sense I would appreciate a nudge in the right direction. I have succeeded in writing this app as a dashcode webapp but I would like to implement it as a native iphone app.

    Again, Thanx for the tutorials so far and keep em coming.

  • Ron

    Brandon: Thanks so much for the tutorials! They’ve been extremely helpful.

  • http://www.svenkubiak.de kubi

    Thanks you ver much for this Tutorial! Came at the right time, as i was stuck on the SQLite-Books-Example. Really looking forward to the next parts!

  • http://icodeblog.com Brandon


    To hide the keyboard, put this code

    [txtName resignFirstResponder];

    in the method that gets called when your button is pressed. txtName of course will be the variable associated with your text box. That should hide the keyboard.

    Thanks for posting!

  • ragingfire

    great tutorials! And yes, I am very interested in the tabs that shardayyy mentioned. keep ‘em coming! i am learning a lot. :-)

  • shardayyy

    I came across this nice GUI for the SQLite Database that is an addon to firefox. Check out

  • http://icodeblog.com Brandon


    that seems very helpful, thanks for the link.

  • Todd

    Hi Brandon, basic question for you. Why does the DB get copied to the documents folder? Can’t it be accessed or edited in it’s default location?

  • bobcubsfan

    Hi Brandon

    What is the best way to use a variable instead of hard-coding text in a file?

    For example, “todo.sqlite” is used in several places. Could we not use a constants.h file with often used text? That way if something changes, only the entry in the constants file would have to be changed.

  • bobcubsfan


    thanks for the firefox link. What a time saver!

  • bobcubsfan

    Question about sqlite manager. how does one create a field of a specific length? Example: State should be 2 VARCHAR.

  • http://icodeblog.com Brandon


    Good question. I’m not 100% sure I was just following Apple’s conventions. But if I had to make an educated guess I would say it’s a permissions thing.

    From my experience with iPhone hacking, directory security is strange for apps. The Documents folder should have the most open permissions.

    Sorry I can’t give you a strait answer.

  • http://icodeblog.com Brandon


    Yea, you could assign a variable to the db name however I don’t foresee changing the db name and if so, there is always find and replace :) . But yea you could do a static constants object and called like:


    I think this would only be practical when your app has a lot of global constants. Usually a game would warrant this type of design. Otherwise, you shouldn’t allocate another object for 1 or 2 constants.

    Probably the best practice for this situation is declaring an NSString property for the database name inside of todoAppDelegate.h and initialize it in the applicationDidFinishLauching method before the db methods get called.

  • Darryl

    Just wanted to say thanks on the resignFirst Responder tip.
    I tried it and it would work once and then any subsequent attempts would crash the program. I thought it was the first responder thing and went and looked at all the class info for textfield and UIResponders and couldn’t figure it out and then after looking closer at my own code I noticed a mistake in allocating and releasing an NSString.
    After fixing that the resignFirstResponder works great.

    Also in response to Todd’s question I thought I’d look in the comments found in the SQLiteBooks example and found this

    // The application ships with a default database in its bundle. If anything in the application
    // bundle is altered, the code sign will fail. We want the database to be editable by users,
    // so we need to create a copy of it in the application’s Documents directory.

    Evidently the iphone does some kind of a hash on the app bundle and if you change the original sql file it changes that code and the iphone refuses to run the app anymore.

  • http://icodeblog.com Brandon


    Glad it worked for you and great find on the db thing! That really clears that up.

  • http://www.svenkubiak.de kubi

    @Todd, @Brandon
    Looking at Apples SQLiteBooks Example the code signing might be the reason why the database is copied. Look at the comment in “applicationDidFinishLaunching” in “AppDelegate.m” in the SQLiteBooks Example.

    “[...]If anything in the application bundes is altered, the code sign will fail. We want the database to be editable by users, so we need to create a copy [...]“

  • http://www.newgadgetsguru.com rramnel

    Hi Brandon, really useful stuff. Learning a lot from your tutorials. Thanks a lot…

    FYI below is a website where you can create/browse sqlite databases using a GUI, easy to use..

    and when is part 2 of the tutorial? can’t wait…

  • fernando

    great tutorial
    my only problem is with the updating of data on the UITableView
    your tutorial yet does not adress it and so am very interested how this is achieved
    been trying lots of different methods but it doesn’t work the tableview in my root controller does not update with the new data and I know my app inserts new data cuz u see it only after I close and open by app
    so really eager for your next tutorial

  • bobcubsfan

    I feel like such a criminal.

  • http://icodeblog.com Brandon


    Prob explains why it has been weeks and I have yet to be accepted to the developer program. I’ll prob get a cease and desist letter soon…LOL

  • bobcubsfan

    I hope not. You have been a great teacher, Master Yoda!

  • Aaron

    I cannot seem to get the data to display in the table. There are no errors.

    Also when I use your code I just get a callstack.


  • http://icodeblog.com Brandon


    When you say “use your code” are you referring to the sample code?

    This current tutorial will not display data in the table (yet). I will release the part 2 some time this week which will detail this.

    If you would like to post some of your callstack here, I would be happy to help you with your issue.

    Quick question: Are you running the latest version of the iPhone SDK?

  • nandihno

    cool so some time this week the next tut??
    like i said..i want to know how the RootViewController gets refreshed with data…
    ! ;)

  • Adam

    Wow Brandon, you are putting your ass on the line for us. haha

  • kiwi

    Nice examples mate!
    Would be nice to have the conclusion to this series soon :)

    Also, another tutorial on how to save stuff from a NSMutableArray to the iPhone but NOT using SQLLite


  • Aaron

    Hi Brandon, I am running 3.1

    Ill try the latest to see if that helps.


  • Aaron

    ok … that worked..

  • Michael

    I built a small program using your tutorial as a template. Great template by the way. Works beautifully on my mac. However, when I go to deploy it to the phone, I get “2008-08-27 18:40:38.658 iQuit[344:20b] *** Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘Failed to copy the database. Error: Operation could not be completed. No such file or directory.’”

    Ahhhg – Any ideas?

  • iSam

    wheres part 2-3-4?

  • http://icodeblog.com Brandon

    They are coming sorry for the delay.

    School > me

    Part 2 will be up by Monday if not earlier…I promise.

  • bobcubsfan

    What happened to my posts answering questions?

  • http://icodeblog.com Brandon

    Hmmm. that is odd, I haven’t deleted any posts

  • bobcubsfan

    Maybe it was in a different thread. How about a link to “My Posts?” Apple does this. Apple also has a link to “My questions.”

  • http://icodeblog.com Brandon

    I’ll look for a WordPress plugin to do that. I you find one, send me the link.

    If one does not exist, I can write one at some point…

  • bobcubsfan

    Went to WordPress web. Difficult to find anything meaningful.

  • Lali

    Great tutorial! It helped me a lot. I like your explications, they are clear and comprehensible.
    Can you explain please the CreateEditableCopyIfNeeded procedure as well?
    I’m new to this platform.

  • Bruce

    Nice tut!! and nice blog too, I am sharing this tut on my own blog, thanks dude!

  • http://icodeblog.com/2008/09/02/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-2/ iPhone Programming Tutorial – Creating a ToDo List Using SQLite Part 2 | iCodeBlog

    [...] iPhone Programming Tutorial – Creating a ToDo List Using SQLite Part 1 [...]

  • Jenny

    Thank you! These are great tutorials. They’re well done, easy to follow and work! I know it must take a lot of time for you to create one and I’m anxious for more when you get a chance. Thanks again — You’re a great teacher!

  • Simon Marshall

    Great tutorial…just wondering how you set your “sqlite3_stmt” and “SQLITE_OK” to those colours?

    any info or tips greatly appreciated.

    keep up the good work :)

  • http://icodeblog.com Brandon


    Are you talking about the syntax highlighting. XCode should be doing that automatically for you. I didn’t do anything special.

    Perhaps you need to update XCode. Also, try quitting your app and starting it again…

  • http://icodeblog.com/2008/09/10/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-3/ iPhone Programming Tutorial – Creating a ToDo List Using SQLite Part 3 | iCodeBlog

    [...] iPhone Programming Tutorial – Creating a ToDo List Using SQLite Part 1 [...]

  • Pete

    Thanks Brandon, this has been a great help…

    I hope you’ll reconsider doing a tutorial on audio & video aspects of the iPhone. Like recording and playing audio and video’s and saving them to sqlite or even displaying them on table views for the user to browse through…

    Am I asking too much? Hehehehehe Hope not…

    Thnks again! :-)

  • Varun Prakash

    I did everything exactly the same as mentioned in the tutorial, still when I build and go the application, it crashes.

    Can you tell me what is a possible issue?

  • Prayag

    when you publish part 4… i am waiting for that….

  • http://icodeblog.com Brandon


    Have you tried downloading the sample code? Post some of your errors so that I can help you troubleshoot it. Also, one major source of error is not importing the sqlite library into your project. Did you complete that step.


    Soon…It’s almost done. Will be out sometime next week.

  • pfargo

    Kinda redundant to add my thanks Brandon but want you to know new people are glomming on.

    Your efforts are greatly appreciated.

  • Dave

    Learned a lot about databases in XCode. Thanks for the excellent examples, but when I compile and run I get no errors but it quits unexpectedly and crashes. I’m guessing I forgot to release something?


  • Dave


    The console error message was that :

    ‘Assertion failure in -[todoAppDelegate initializeDatabase]
    Terminating due to uncaught exception. Failed to open
    database with message ‘not an error’.


  • Dave

    Ooops! My bad. Missing last couple lines of code!
    Fixed now.


  • http://icodeblog.com/2008/09/22/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-4/ iPhone Programming Tutorial – Creating a ToDo List Using SQLite Part 4 | iCodeBlog

    [...] iPhone Programming Tutorial – Creating a ToDo List Using SQLite Part 1 [...]

  • http://www.ChipAndKim.tv Chip

    Hey Brandon, I am extremely thankful for your 4 part SQL Lite database driven application. My background is that I use to be a dynamic database driven application development developer (5 years ago). I mainly used Microsoft’s Active Server Pages with SQL Server and Oracle Databases. I feel very confident with your SQL language and calls. However, though I typed every line of code that you laid out in your tutorial . . . AND . . . have printed out EVERY PAGE of the Apple iPhone & C related documentation from the iPhone Developers Program, I do not understand how to create an application on my own. I would have NO IDEA how (and why) you do what you do, when you do it. I am VERY lost. PLEASE lead me to an “iPhone Applications for Dummy’s” website or book or something . . . EVEN BETTER . . . do you know of a training facility that I could attend in Southern California? Because as it stands now. I am just mimicking your code (and appreciating you for it) and my light is not coming on as to how I would have been able to have done what you do on my own. As you can see, I am anxious to learn. PLEASE HELP ME, Brandon. Thanks.

  • http://icodeblog.com Brandon


    Have you read any of my Hello World Tutorials. I have a few more on the site…They should provide a little more insight for you as the SQL tutorials are a little more advanced. Also, in these tutorials, I have assumed you completed my previous tutorials.

    I don’t know of any training areas. I’m not even sure if they exist as Apple is pretty lame when it comes to their NDA. Even me having this site violates it.

    Read through the earlier tutorials on my site and feel free to post any questions either in the comments section or in the forums.

    thank for reading…

  • http://www.athenadesign.co.uk/blog/index.php/archives/58 iPhone Application And Website Development: All Tools And Tutorials You Need | Athena Design – The Lounge

    [...] a ToDo List Using SQLite – Part 1 -Part 2 – Part [...]

  • Ramit

    Good job Brandon, nicely presented… would’nt be possible without this tutorial

  • Redth

    I’m just getting into iphone dev as a c# coder, and it’s a pretty different experience. I’ve had a heck of a time finding some solid concrete examples to start with that are between hello world, and complicated…

    This looks like the first set of tutorials that hit just the right spot! I’ll be using this first series to start working on. Kudos, and thanks so much!

  • http://icodeblog.com Brandon


    no problem! I would not suggest starting here though. I have some easier tutorials that will get you started on understanding Interface Builder.

    Look in the sidebar of the site. Under the “tutorials” heading. They are listed in the order I write them.

  • http://web.mac.com/ostros/iWeb/iPhone%20Apps%20Entre%20Pilotes/HOME%20%28FR%29.html Deamb

    Hello Brandon,

    I have 3 Apps published on the AppStore, but I love your tutorials !
    They are very basic apps, oriented towards aviation needs, and I am learning a lot from you !
    Please keep it up !

    One question though, already asked by Phil on Aug 19th (but I haven’t seen a response) :
    Can we build the database with a GUI ?
    The one I have in mind has about 200 entries, and it would take me forever in Terminal !


  • http://acloudtree.com backwardselvis


    You do not have to do each sql statement line by line

    1) enter into the sqlite3 command prompt

    2)Copy and paste the text below and press enter

    CREATE TABLE test(pk INTEGER PRIMARY KEY, text VARCHAR(25), priority INTEGER, complete BOOLEAN);
    INSERT INTO test(text,priority,complete) VALUES(‘Take out the trash’,3,0);
    INSERT INTO test(text,priority,complete) VALUES(‘Do Computer Science homework’,1,0);
    INSERT INTO test(text,priority,complete) VALUES(‘Learn Objective C’,1,0);
    INSERT INTO test(text,priority,complete) VALUES(‘DIGG this tutorial’,2,0);

    This should allow you to easily recreate databases.

  • Shani

    Hello Brandon,,

    i have changed mine data base file but my application give old reference . and does not leave old reference. mine application could not fine updated database even if i removed old database reference and also deleted it. so can u plz help me for that . what should i do ? i also removed build filed. then also i could not use new db.

    i am too much confusing and project deadline is near . so plz as soon as give solution for that.

    Thanks Regards

  • http://web.mac.com/ostros/iWeb/iPhone%20Apps%20Entre%20Pilotes/HOME%20%28FR%29.html Deamb

    @ Backwardselvis :

    Thanks for the tip, but I still have to write all 200 entries into something like text editor before I paste it into terminal !

    Anyway, I guess I’ll do it ! :)

  • http://icodeblog.com Brandon


    If I understand your question correctly, you simply need to uninstall you application from the simulator. This is done by clicking and holding your mouse down on the “home” screen in the simulator. The app icons will “wiggle” and you can click the “X” in the corner. It will prompt you to remove.

    After doing this, add your new database to your project and the reference will now match up.


    Have you tried Googleing an SQLite GUI. I haven’t seen one. I think in the comments of another post someone suggests a web based one. I’ll post if I find one.

  • http://web.mac.com/ostros/iWeb/iPhone%20Apps%20Entre%20Pilotes/HOME%20%28FR%29.html Serge ostrowsky (Deamb)

    No brandon, no luck so far, except 250$ ones, I haven’t found anything…

    I’ll look for a web-based one though

    Thanks again

  • Ulthor


    I’ll add my kudos to the others. Thanks very much for your effort in writing these tutorials. I would not be able to get started as an iPhone developer without you. You Rock!!!

  • Ulthor

    OK, an actual question:


    @interface todoAppDelegate (private)

    The syntax here looks like a category named “private”. Is that true?

  • http://icodeblog.com Brandon

    Not quite… What this line is say is, we are declaring a private interface for this class. It’s sort of like declaring a road map for this class.

    Thanks for reading…

  • Neo

    Hey guys,
    Thanks for this tutorial Brandon!

    For those of you who want to test the code after completing this tutorial, just add this code to RootViewController.m:


    #import “todo.h”

    ..and then..

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

    todoAppDelegate *appDelegate = (todoAppDelegate *) [[UIApplication sharedApplication]delegate];
    return appDelegate.todos.count;

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *MyIdentifier = @”MyIdentifier”;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];

    todoAppDelegate *appDelegate = (todoAppDelegate *) [[UIApplication sharedApplication]delegate];
    todo *t = (todo *)[appDelegate.todos objectAtIndex:indexPath.row];

    [cell setText:[NSString stringWithFormat:@"%@ - #%d", t.text, t.primaryKey]];

    // Set up the cell
    return cell;

    Maybe you want to add this to your tutorial Brandon, shows some progress ;)
    Thanks anyway!

  • http://icodeblog.com Brandon


    Thanks for posting this. The reason that I didn’t add that code to this tutorial is I show how this is done is part 2 of the todo series. I should probably make that more clear by linking to the next tutorial at the bottom.

    Anyway, great job man!

  • Neo

    Brandon: Yes you’re right, I know that there are 4 parts. But I just did it for myself – to check if the sql database works -before starting with part 2!

  • Albert


    not sure what’s going on but when I try to launch the App I get a “Unable to read symbols for “/System/Library/Frameworks/UIKit.framework/UIKit” (file not found).” I know this is not where the UIKit framework is located and I can’t figure out how to change it. Your help is much appreciated.

  • Ade C

    Just wanted to say Thanks

    As a tip for noobs like me, i have found that hitting the Build and Go button frequently through the tut helps in finding errors/typos earlier which makes them easier to fix. Maybe a suggestion for Brandon to put a B&G instruction after each section to suggest that the app should build at that point with no errors. Believe me, I do this a lot now and it helps me a lot!!!

    Anyway, gotta go… I’ve got the next part to follow :)

    See you in Prt2 comments!!

  • http://www.joegaudet.com Joe

    Hey, great tutorial, however I seem to be having trouble with something.

    I’ve followed your instructions quite closely, but cannot seem to make changes to the database in a programmatic way. That is to say that, I have a dehydrate routine, but the changes it makes do not seem to persist, the next time I load the program, the previous values are still present… this is also true when I directly edit the todo.sqlite db from the terminal… so far as the project is concerned everything should be working…

    Any ideas ?


  • http://vbharat.com/Programming/2008/10/21/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-1 vBharat.com » iPhone Programming Tutorial – Creating a ToDo List Using SQLite Part 1

    From vBharat.com » iPhone Programming Tutorial – Creating a ToDo List Using SQLite Part 1…

    Learn to create a simple todo list for the iphone. Great iPhone programming tutorial for beginners to intermediate….

  • Stefan

    You should’ve at least mentioned in one sentenced that your example is borrowed from the Apple examples … but good comments, though!

  • http://icodeblog.com Brandon


    What do you mean man? Did you miss the line that states

    “Much of the code for these has already been written for us inside of Apple’s SQLBooks tutorial”

    implying that some of this code came from Apple’s examples. What else would you like me to add?

  • Shani

    Hello Bradon..

    it’s nice tutorial and too much help in to create new application.

    one problem i have …
    i have changed the name of project then i got error in sqlite3_prepare_v2 statement. it gives error in sqlite_error.

    so can please give any solution for this ? what should do now ?

    Thanks Regards,

  • Jerod

    Just wondering where the NSAssert1 will output its errors. I am not seeing it print anything to the Xcode console.

  • http://www.kylehayes.info/blog Kyle Hayes

    How come in the initializeDatabase method you don’t initialize the self.todos directly with the alloc/init methods and instead you create a temp object?

  • http://www.virtueinfo.com hemalimojidra

    thank you.
    this tutorial is very helpful to me

  • http://www.virtueinfo.com hemalimojidra

    how can i open .sqlite file,

  • Dmitry

    if I use NON Navigation Based Application Project with link to SQLITE i have error of building aapp. Why?????? Just try to add link and build empty project. Please HELP!!!

  • ObiOne

    It’ll be awesome if you showed us how to do this with some Tabs. Also, I’m new and I’ve been following along your tutorial. I’m trying to add another text box called text1 and I added it to the sql table. But everytime I run the app… it crashes and says there’s no column called text1. Any help would be appreciated.

  • http://www.cheapcoachhire.com Coach Hire

    Hello. I think you are eactly thinking like Sukrat. I really loved the post.

  • http://iappdevs.blog.co.in/2008/12/27/todo-list-application-iphone-programming/ Todo List Application -iphone programming | iPhone App Devs

    [...] Add the SQLite3 Framework [...]

  • http://www.duivesteyn.com.au Adelaide Web Design

    Cheers, this is an amazing tutorial, great work.
    Good luck with the child too!!

  • http://newsmavens.wordpress.com/2008/12/27/links-for-2008-12-27/ links for 2008-12-27 « Brent Sordyl’s Blog

    [...] iPhone Programming Tutorial – Creating a ToDo List Using SQLite Part 1 | iCodeBlog If you have been following my tutorials, you know that we have been working primarily with UITableViews. This is mostly because SO many applications can be developed using this simple control. This final UITableView tutorial will be taking all of the skills learned from previous tutorials, putting them all together, and adding SQLite to create a prioritized To-Do list. I will also be showing you how to add multiple columns to your table cells and we will be exploring some of the other controls that the iPhone has to offer. What good would the tutorials be if we didn’t use them to create something useful. (tags: iphone development) [...]

  • rob

    What a waste of time! This is just an incomplete rehash of the apple sqlbooks tutorial.

  • http://nuthinking.com christian

    Thanks a lot for the tutorial!
    One question, how should I do if I would like to bind more parameters? For instance:

    const char *sql = “SELECT text FROM todo WHERE pk=? AND px=?”;

    Thanks, chr

  • http://nuthinking.com christian

    Ops, I presume the second parameter specifies the index :)

  • Inscrutable

    Maybe this is simpler than I think, but how do we use multiple tables? how do I tell the app which one i’m trying to get at?
    In the project it has something like this: const char *sql = “SELECT pk FROM thetable”;

    If i want to initialize another table and be able to query it independently, do I do something like this:
    const char *sql1 = “SELECT pk FROM thetable2″; ?

    Thanks for any input (BTW your tutorial explained alot).

  • http://benipsen.com Ben Ipsen

    I’m getting “error: ‘database’ undeclared (first use in this function)” compile-time for two lines:

    in todoAppDelegate.m:

    if(sqlite3_open([path UTF8String], &database) == SQLITE_OK)

    and in Todo.m:

    NSAssert1(0, @”Failed to prepare statement with message ‘%s’.”,sqlite_errmsg(databse));

    I’m curious about my arguments not working correctly in the second case as I also had trouble with the initWithName method arguments in the fruit example. That aside, it seems the first instance (passed as reference) should definitely work. Please let me know if there’s a place I may have missed the declaration.


  • Another Ben

    I’m getting a “_TERMINATING_DUE_TO_UNCAUGHT_EXCEPTION__” error and am unsure how to use the debugger – no matter how early in the program I set my break point, I get that error!

    Could I get a link to a debugger-how to, or some advice in general? Thanks!

  • Brandon

    While my answer to this question is probably in this list of tutorials, I have yet to find it.

    I have an app setup and working. It consists of 3 tab’s. Two tabs display a tableview with a list of names from two plist files. These lists are in alphabetical order with an index. The third view simply shows my logo and details about the app.

    I would like to take the first view, a table view, and have it display details about the name that the user click on in the table. I want to keep my list grouped in ABC order and keep the index on the side. My details for each name are going to consists of many lines of text, and maybe a picture icon.

    I am having trouble finding a place to store this detail data and how to call it in when a user click on the related name in my first tableview.

    The second tableview is just a tableview, with no details.

    I have been stuck on this for days. Any help would be great! Thanks for all the great advice in these tutorials!!

  • rabi

    Hey i am very big fan of iCodeBlog.. i learned so much from here !!
    now i have some confusion regarding ,

    “create a new folder in iPhone” while running my application;
    so i can store user modify data !!

    since i dont know the directory structure of iPhone ..

    so please help me regarding this..
    i request other reader as well …

  • Y Ramesh Rao

    Hey Man Bardon… Thanks man…
    I was working on this simple app where in the user sets in the to-do list then the app helps him to remember things by just giving him simple Alarm type thing… How should i work that out…

    Please help me out with this Dude…

  • Andy

    Great tutorial. Thanks for doing this. One quick (or not) question. How would you modify this to accommodate a database with more than 1 table? In the app I’m working on I have two tables and each table has a corresponding object.



  • http://www.bestfruitmachines.me.uk best fruit machines

    the comments here are having a laugh – i’ve added your blog to my netvibes account, keep up the good work :)

  • Alok

    Hi, i have some simple problem. i am using the sqlite to save data.In My application when i Insert the some record into database table then record inserting properly, but next time when i am re-inserting the record after closing the application. my database file not taking changes. it showing previous record again and again. i not getting any Query error at Console, Console saying that I am inserting the record with row id. but my database file is not getting the Changes.

    What am i missing something. or when i close my application suddenly my database file not committed with new record. Did i have to code at the application terminate Point?

    Thanks in Advance.

  • Georg

    Thanks for an excellent tutorial.

    I’m trying to figure out how to get the data from all columns in one row, where primarykey is equal to variable “i” and put the data in a nsmutablearray, one column per array entry.

    Here’s an examle
    contacts table would contain:
    pk(INTEGER), surname (VARCHAR), lastname (VARCHAR), email (VARCHAR).
    sql: “SELECT * FROM contacts WHERE pk = ?”
    and ? would be replaced by variable “i”

    Any pointers in the right direction would be much appreciated


  • http://bheemtal.com krishna

    Great article.

  • http://myegm.com Tim

    Great tutorials Brandon,

    I’m getting a Linking errors

    “_sqlite3_colum_int” , referenced from:
    -[totdoAppDelegate initializeDatabase] in todoAppDelegate.0

    “_sqlite3_colum_text”, referenced from:
    -[Todo initWithPrimaryKey:database:] in Todo.o
    symbol(s) not found
    collect2: ld returned 1 exit status.

    any help would be appreciated I really want to continue to part 2.

  • http://myegm.com Tim

    Might Help if I spell Column right. All fixed thanks for the great tutorials.

  • http://none pierre

    thanks Brandon, I’m learning the new trade. I went through your tutorials. I got stuck with the Sqlite3 part one. What do I do with the follow error, “__terminating_due_to_uncaught_exception__” when I run my app with the simulator. When compiled no errors shown.

  • Joel

    I must say I am learning alot from your tutorials. Much appreciated.

    if you could help with this that would be great:

    on todo.m I am getting an error on @synthesize primaryKey,text;

    its saying “error: type of property ‘primaryKey’ does not match type of ivar ‘primaryKey’

    this is the property I have for it

    @property (assign,nonatomic,readonly) NSInteger primaryKey;

  • Joel

    oh nevermind found the error, thank you

  • Tommy

    Thanks for the tutorial. It has taught me a lot. Just one question. If I wanted to do a QUERY for a specific record, from a picker for example. Would I add a new method and select statement or just alter the original “SELECT text FROM todo WHERE pk=?”

    Thanks in advance.

  • http://deepfocustech.com Matt

    Hey Brandon!

    I’ve written tons of db code, but never used sqlite3, so this is just the right amount of info for me. Thanks.

    One thing I’d suggest for efficiency’s sake is to do avoid doing nested queries to to retrieve all of the values from the table.

    I wrote the code for my app to essentially do the following:

    syntactical, schema and other liberties taken…

    pepare(db, “select pk, text from table”, &statement);
    while(ROW == step(statement))
    Todo * t = [[Todo alloc] initWithStatement:statement];
    [todos addObject:t];
    [t release];

    initWithStatement retrieves all of the columns into the Todo object rather than issuing another select statement. Nested queries are expensive. Since sqlite is in-memory and file-based, it likely doesn’t make that much of a difference, but if you were accessing a DB over a network connection it would make a huge difference.


  • Alejandra Gonzalez

    Hi Brandon!! great Tutorial!

    I have a question, can I have my SQLite database in a remote server and make queries from my iPhone app?
    do you have another tutorial showing something like that?

    thanks in advance for the info

  • Ben

    if you are getting the error:
    “_TERMINATING_DUE_TO_UNCAUGHT_EXCEPTION__” (or your app just quits and there is a popup asking you to report it)
    “self.text = [NSString stringWithUTF8String:(char *)sqlite3_column_int(init_statement, 0)];” in Todo.m with
    “char *pointer = (void *)sqlite3_column_int(init_statement, 0);

    if (pointer == NULL)
    self.text = nil;
    self.text = [NSString stringWithUTF8String: pointer];”

  • Chase Acton

    I am EXTREMELY interested in taking this tutorial that you made and having different lists in different tabs, using a ui tab view. I am new to developing iphone apps and have been pulling my hair out for the last month trying to get multiple to do lists, each in a different tab. I saw that other people would like a tutorial on this as well.

    I wold be so grateful for a tutorial and/or the xcode project file on how to accomplish this.

    Thank you SO much.


  • Graham

    I don’t know if you did it already, but I’d love a line-by-line breakdown of some of the more dense code blocks. It’d help me understand what’s going on

  • http://unlikelyteacher.com Paul


    Thanks for this detailed tutorial on SQLite.

    However, I’m a bit concerned on the number of round trips required to fetch the information. Would you also have information on how to use callbacks properly?

    Thanks again.

  • Jace


    That was a great tutorial on displaying the database.

    Because I have an Oracle database so I do not wish to code it again in SQLite 3. Is there any way for the SQLite 3 to contain an Oracle database in it and displaying it on the simulator?

    Thanks, :j

  • http://rainiazahmad.com/?p=2724 Top 10 Tutorials to Develop iPhone Apps : Rai Niaz Ahmad

    [...] Tutorial Link [...]

  • http://www.rogerstringer.com/interesting-links/ive-reading-week-july-312009 What I’ve been reading this week (July 31/2009) – Roger Stringer

    [...] iPhone Programming Tutorial – Creating a ToDo List Using SQLite Part 1 [...]

  • Rutger


    I really like your tutorial, great work !

    I’m looking for the SQLite Books example but I can’t find it anywhere. Where can I download this demo project ? It’s not on the Apple Dev Center site ?

    Any suggestions ?

    With regards,


  • Ryan

    Hi Brandon,
    This is excellent stuff. Have got it all working and loving it.
    There is however one thing that I would like to add… a UIView which shows a summary of information, and then with a button from this view I am taken to the tableview of the details and can then navigate to each one for more detail.
    So I want my opening screen to show a summary – in my case – average miles per litre. This is going to be a graphic plus the value plus a button to then go the tableview showing me the entries that make up that average.
    Do I need new viewController to achieve this and how do I connect it up?
    Any help or direction to some code to achieve this would be most appreciated.

  • Quaero

    Great Tutorial!!!

  • Andrea

    ho scaricato il sorgente, se simulo lo shake non succede nulla, utilizzando per esempio lo shortcut ^(command)Z.

    E’ Normale?

  • ujku malit

    i want to play sound on – (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    pliss help me

    #import “mainview.h”

    @implementation mainview

    - (IBAction)A1 {
    SystemSound = [[sounds alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@”A1″ ofType:@”mp3″]];
    [SystemSound play];


    - (IBAction)B2 {
    SystemSound = [[sounds alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@”B2″ ofType:@”wav”]];
    [SystemSound play];


    - (IBAction)C3 {
    SystemSound = [[sounds alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@”C3″ ofType:@”wav”]];
    [SystemSound play];


    - (IBAction)D4 {
    SystemSound = [[sounds alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@”D4″ ofType:@”mp3″]];
    [SystemSound play];

    - (IBAction)GR1 {
    SystemSound = [[sounds alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@”GR1″ ofType:@”mp3″]];
    [SystemSound play];

    - (IBAction)AL1 {
    SystemSound = [[sounds alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@”AL1″ ofType:@”mp3″]];
    [SystemSound play];



    #import “sounds.h”

    @interface mainview : UIView {
    sounds *SystemSound;

    - (IBAction)A1;
    - (IBAction)B2;
    - (IBAction)C3;
    - (IBAction)GR1;
    - (IBAction)AL1;
    - (IBAction)D4;

  • iPhoneNewbie

    Hi, Firstly, great website. I really appreciate all the work you put in. I have a silly question. Coming from the Java world, I’m struggling to understand why we do things this way:

    NSString tempString = [[NSString alloc]@”Some String”];
    instanceVar = tempString;
    [release tempString];

    how about just:
    instanceVar = [[NSString alloc]@”Some String”];

    That way we don’t have to declare it onto a temporary variable (by assigning it directly to the instance variable) and later having to release it?

  • Ankit

    Query To Delete the Whole Database.

  • Brooks

    How would you put a “header” (i.e. “Priority”, “Task”) over the rows? My app has more columns and they are numeric so a header is needed.


    (great website)

  • td

    Is there a way to copy the database over anyway even if it exists? For example I’ve inserted some rows to my sqlite database outside of Xcode/Iphone. I want to the application to either delete and recreate the database or overwrite the database with the new one so it will have the new rows. If I just make the changes the database and have the code recompile, it won’t have the new rows.

  • http://sadas ASSHu

    Nice Tutorial LOlzzzzzzzzzzz

  • Kristofer

    I cannot find libsqlite3 when I search for it .. I tried everything .. When you go to add existing frameworks .. It doesn’t even show a single one, i tried typing it in a couple times. Doesn’t even find libsql anywhere?!?! Help please?! I want to do this tutorial so bad

  • johhny

    A 101 question

    Why is it @property(nonatomic, retain) NSString *text;
    and not @property(nonatomic, assign) NSString *text;

    I understand that Assign will not increment the reference counter as Retain will do. But why use Retain, since it’s a member of the todo object and we won’t use it with anything else.

  • Jeremy

    Downloaded your code ran it in Simulator 3.0 and when it loads I get no data, just empty rows.

    The SQL Works fine I ran in terminal and it pulls back correct data.

    I get a warning: Format not a string literal and no format arguments in todoAppDelegate.m

    Would not be so surprised if I had coded as I create typos all of the time. Can someone confirm that it works in 3.0

  • mora

    – – – – – – – – – – – – – – – –

  • Ron

    Had problem when trying to run a example on simulator. Problem was the active SDK was not selected. Click the drop down box in upper left hand corner of xcode and choose the proper SDK.

  • Jay

    Jeremy said that he downloaded the code. Where did you download it from? Do not have to retype all this code?

    This is the best tutorial site I have ever seen. I have chosen this one as my first attempt to start learning iPhone development.

    I am getting an error when I go to build and run this. The problem is with line:

    Todo *td = [[Todo alloc] initWithPrimaryKey:primaryKey database:database];

    The error is: bothe “Todo” and “td” undeclared. HELP!

  • Rob

    Great tutorial. Thanks.

    Another option for adding the libsqlite3.0.dylib to the project:

    1. Select the target (todo) in the groups and files panel.
    2. Click the info button
    3. Under the General tab, click the + button below “Linked Libraries”
    4. Select libsqlite3.0.dylib and click the Add button

  • http://brandonpate.org/?p=15 SQLite tutorial « Ramblings
  • http://www.crystalminds.nl Mark

    Great tutorial! I made SQLite even more simpler with a library which I would like to share the CMSQLiteDatabase library to be more precise. With this it’s really easy to create and manage your database from within an application.

    You can download it for free at . Enjoy.

    Less writing, though it’s always nice to have background information on how SQLite can be raw implemented.

  • http://www.timewalksoftware.com sam

    I just upgraded to 3.1.2 and the new stuff ad this will not compile or run. The frame work files are listed in red in the groups and files section. Is there an updated version of this code or something?

    - Sam

  • Eddie


    Great tutorials. It is a great start but I have a problem with my sqlite3. I’m on Snow Leopard with xCode 3.2 and I was trying out your tutorial on sqlite3 but I got an error, “file is not of required architecture”. Do you know of any solution? Thanks

  • hugo

    hi brandon!

    i tried to check if someone has mentioned this before… but the SQLite DB can be easily created with Mamp (which has a free version)… and with a bit of work you can migrate bigger DBs through the phpMyAdmin… have not tried it yet, but seems pretty simple (i will try and post the results)…

    all the best! you rock!

  • sam

    Hi Brandan,

    Great work & tutorial for the new ones like me. I have used you example and tried a very simple modification – instead of NSString, I used the UITextField, and tried to display name and value in the ViewDidLoad. When I run, I am having ‘out of memory’ error at “select name, value from tab1″ prepare statement. Could not figure the issue. Can you help ??

    I am trying to do is add / update rows with Update button, and display the rows from DB while appl starting.

    Just started learning ..

  • dgraham

    Hi, great tutorials. Really love them. However I ran into a problem.

    When I finish this tutorial no list is displayed when I compile and run the code… In the Fruits tutorial we edited the

    numberOfRowsInSection and

    functions to display the fruits. But, in this tutorial, you don’t mention doing that. Is that why nothing displays? However, in your part 2 of this tutorial you start off with it display stuff despite saying at the end of this one that “it won’t display anything”.

    Sorry I am confused!


  • dgraham

    Totally mis-read the start of your next tutorial. Please ignore my stupid question above…

  • CW

    Anyone have an answer to Eddy’s question above?
    “file is not of required architecture”

  • CW

    I am trying to build against an iPhone running 2.2.1. I can build to the simulator while it is set to use 2.2.1 and all is fine but when building for the device it fails with “file is not of required architecture” referring to libsqlite3.0.dylib

  • Girish

    Please tell me that if inside the project folder that i downloaded as a sample code if we delete or add a row from database then it’s not updated when the application is executed next time…while update successfully occurs in database and visible when checked through select * …. query….

  • Girish

    Actually it doesn’t matter how many rows you add in database from terminal…addition of deletion of rows is possible only via the edit and add buttons provided….. Isn’t it a required rectification….

    Brandon please take a check into it…..If the data is not updated in the database then where does it comes from next time when executed after update by the add or edit buttons provided by you????

  • Chet

    I’d like to second Rob’s comment above. This is a less error-prone way to import frameworks than using the search option. It’s hinted at in Apple’s Core Data tutorial (), although it’s a bit unclear (“Use the General pane of the Info window for the application’s target”).

    There are at least two ways of accessing this dialog:

    1. Expand “Targets” in the “Groups and Files” panel.
    2. Perform either of the following actions:
    a. Select the target (“Todo”), and click the “Info” button found near “Build and Go” at the top of the Xcode window.
    b. Right-click the target (“Todo”) and choose “Add” >
    “Existing Frameworks…”
    3. Click the plus sign in the lower left corner of the window.
    4. Select libsqlite3.0.dylib and click Add.
    5. Close the Info window.
    Select the target (todo) in the groups and files panel.
    2. Click the info button
    3. Under the General tab, click the + button below “Linked Libraries”
    4. Select libsqlite3.0.dylib and click the Add button

  • Shane

    Thanks for great tutorial, i have two queries when i run my code and was wondering if any of you guys could help me.
    In InitializeDatabase we have the lines:

    Todo *td= [[Todo alloc] initWithPrimaryKey etc

    Is this suppose to be todo *td=[[todo alloc]? etc When i have Todo i get the error message ‘Todo’ undeclared.

    Also in the line, if (sqlite3_open([path UTF8String], &database) ==SQLITE_OK){

    i am getting the error ‘database’ undeclared. Sorry if these seen like stupid questions but i an just a beginner and am trying to do as many as tutorials as possible. Also does anyone know any other good tutorials like this?

    Thanks in advance

  • Shane Courtney

    Hi Sorry, spelt class todo.m instead of Todo.m. Still getting the error ‘database’ undeclared with the line
    if (sqlite3_open([path UTF8String], &database) ==SQLITE_OK){.

    Can anyone please let me know what i could be doing wrong. Many thanks, Shane

  • Jeff Bloch

    Can the SQL database be maintained remotely on a server, rather than on the iPhone itself?

    I would like to be able to send a Yes/No questions to thousands of people and have their responses, and some other data, be added to a remote database to be analysed later.

    If so, what would be required on the server side?


  • neil

    Don’t know, what I’m doing wrong. The only thing I get is a blank table view and a blank navigation bar, although the SELECT is fine.

    iPhone 3GS, German

  • Viswajeet

    Hi Brandon,

    I am like a new born baby, in this world of iPhone Development, and you are like a Father to me in this world, making me learn the basics by your great tutorials…

    Well currently I am finding hard to remember the various syntax and the semantics of iphone coding..but with the passage of time I will cop up with that…

    The thing that I want to know from you currently is that, if i want to develop a application in which I want the Database to be shared by all the iphone users who get the setup of my application on their cells, then is that possible..

    And if possible then
    how the DB should be created
    where it should be stored
    how the connection to the DB should be established.

    Please Reply to this comment ASAP…

  • Marston

    Hi Brandon,

    I think your blog is the best iPhone development blog I have run across. I like the combination of instruction, examples and downloadable sample code.

    I am writing because I was wondering if you had any tips for troubleshooting a particular problem I am having with this tutorial.

    Everytime I try running the code I get this error: ”

    ‘ToDo’ undeclared (first use in this function)”

    right at the point where I try to use the ToDo class in the app delegate class initializeDatabase method (e.g. ToDo *td = [[ToDo alloc]…).

    I made sure to import the ToDo.h class in the ToDoAppDelegate.m file as well as make sure I am importing the framework into the ToDoAppDelegate.h file.

    Any thoughts?

  • Marston

    Hi Brandon,

    I got to thinking that maybe XCode wasn’t able to find the ToDo.h file from the AppDelegate.

    In order to test this, I just dropped the ToDo .h and .m files and added TewDew .h and .m files with all the same code inside them.

    Now everything works just fine. Maybe somehow XCode was retaining a path outside of the file I was trying to specify.

    In my further searching for the error I got before, I did see people reporting a similar issue. Any thoughts?

    Thanks Again,

  • Gig

    Cannot find libsqlite3.0.dylib in my mac! Where can I find it?

  • Minha361

    hi please tell me why the code (iPhone Programming Tutorial – Creating a ToDo List Using SQLite Part 1) don’t run on Simulator – 3.1.2 how fix thix error. thanks very much

  • http://magichand.org/?p=212 magichand Interaction -魔法交互 – iPhone Application And Website Development: All Tools And Tutorials You Need

    [...] a ToDo List Using SQLite – Part 1 -Part 2 – Part [...]

  • Frank M

    Hey Brandon!

    I have the same problem as a few have and no one gave us an answer. In todoAppDelegate.m, I have an error with :
    Todo *td = [[Todo alloc]…
    ‘Todo undeclared’
    ‘td undeclared’

    Can you help us out? Thanks!

  • Mr.kang

    I had the same problem. I had my todo classes named : todo.h and todo.m instand of Todo.h and Todo.m. Not it’s fully working.

    Be carefull with the cases !

  • Kimberly

    Never pick a framework based on “whichever 1 is the biggest… must be the correct one”.


    Are you kidding me?????

    Pick the *POINTER* file… and it will *ALWAYS* point you to the correct one.


  • Paula

    > todo.h and todo.m instand (sic) of Todo.h and Todo.m

    The case of the filenames *NEVER* makes any difference.

  • http://iphoneapp.us/the-complete-iphone-development-toolbox-5/ The Complete iPhone Development Toolbox | iPhoneApp Dev Blog

    [...] Create a To Do List using SQLite – Part 1 of a 4-part tutorial on saving and accessing data using an SQLite database. [...]

  • http://apidocumentation.com/ Jay@APIDocumentation

    Hi Brandon,

    Nice tutorial. I’m working on an application and I populated data in the DB from my within my application internally, when I was building it… I didn’t think about using SQLite3 shell tools to do this.

    The new core-data datamodel should make this easier to do now. This tutorial looks like it was built for an older version of iPhone OS.

    Either way … this is a great, “in plain english” tutorial… Thanks for posting it.

    We need more in “common speak” lessons for this kind of geeky goodness.

    Take it easy,

    Jay at api documentation dot com

  • mobibob

    Perfect. I was looking for the mechanics (not a fluffy wrapper of Apple’s Doc) and you delivered. I found a few minor style issues, but nothing technically wrong. I agree with Jay’s remarks.

    BTW – I just noticed that this is you, Brandon. Your tutorial on twitter was equally helpful! You are already in my favs list, but I will continue to props.

    P.S. I recall that you are writing a book. How is it coming along? Do you need any reviewers? I look forward to purchasing a copy when it is published.

  • lol

    “and it’s prerequisites” != “and its prerequisites”

    Go back to school.

  • jack

    Cannot find libsqlite3.0.dylib in my mac! Where can I find it?

  • http://sqlclasss3.blogspot.com Shyam

    I like


  • http://yourdesignblog.co.uk/technology/develop-your-own-iphone-app/2010/ Develop your own iPhone app — Your Design Blog

    [...] Link [...]

  • http://www.fnfs.co.cc HChouhan02

    Hii I m using xcode 2.0 so there is more errors to make this program.
    Will u please help me to solve that problems????

  • http://www.owenskie.com/?p=10 Owen's Thoughts » Blog Archive » 5 Tutorials to Develop Apps for iPhone

    [...] Sample App: ToDo list using SQLite [...]

  • http://www.owenskie.com/?p=10 Owen's Thoughts » Blog Archive » 5 Tutorials to Develop Apps for iPhone

    [...] Sample App: ToDo list using SQLite [...]

  • certainan

    are the codes downloadable or at least able to copy and paste? =)

    Great tutorial btw!

  • http://www.2jdesign.co.uk Ecommerce Web Design

    Thanks this has been a great article, we are staring offering Iphone services in the next few months and really enjoyed this post.

  • vaishali

    Hi Frank,

    Did you fix this error
    I am getting same problem…..:(


  • http://www.theapplelounge.com/tutorial/app-development-per-ios-i-tutorial/ App development per iOS, i tutorial – TheAppleLounge

    [...] Create a to do list using SQLlite (parte 1). Prima parte di quattro sull’integrazione di database (accesso e salvataggio dati) nelle applicazioni per iOS. Create a to do list using SQLlite (parte 2), Create a to do list using SQLlite (parte 3), Create a to do list using SQLlite (parte 4) [...]

  • Jacqueline

    @ Rob (post from Oct 6th 2009)

    Thanks for posting this information. I had seven libsqlite3.0.dylib in my search results. Selecting the latest version, or selecting the largest file wasn’t working. Going through your steps only identified one file – which worked. Thanks.

  • SaranyaRaj

    just change Todo into todo and next line must contain “todos”…u vil surli get answer …i got dude

  • http://clogwog.net tom

    just going through all your tutorials and thought i’d thank you for putting these up.
    they are very easy to follow and i do 1 an evening (don’t have much time)

    thanks again,

  • http://blog.aws.cerura.nl/iphone-sqlite-example iPhone + sqlite example – Wellner

    [...] Nice SQLite example on icodeblog.com [...]

  • paritosh

    the discription about each and every important statements is really amaizing …
    thanks …

  • Mandar

    Check on this path—>
    /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSilumator3.0.sdk/usr/lib and choose the file libsqlite3.dylib:

  • Kamol

    Thanks a lot…

  • Brian

    Thanks so much, this was a fantastic tutorial for learning to use SQLite.

    I am having 1 issue when reading in a string in the DB that contains a ‘ single quote.

    I have looked at the DB and it is in there (i.e don’t be tense) but when I read it in:
    self.name = [NSString stringWIthUTF8String:(char *)sqlite3_column_text(init_statement, 1)];

    The string no longer contain the ‘ and displays dont be tense, once it is read in.

    I have Googled this and have not found any solutions.

    Can anyone help?

    Much appreciated.


  • http://www.cygnismedia.com/ cygnis media

    I hope you happy and wish you good luck!

  • madhu


  • Ryan

    Very helpful tutorial! You should make a tutorial on how to update your database after you reorder your table cells.

  • John Quinn

    You don’t have to be rude.