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

  • Twitter
  • Facebook
  • Digg
  • Reddit
  • StumbleUpon
  • del.icio.us
  • Google Bookmarks
September 2nd, 2008 Posted by: (ELC) - posted under:Tutorials

This tutorial is part 2 in our series of creating a to-do list.  I will assume that you have completed the following tutorial and its prequisites.

I will be using the code produced from that tutorial as a base for this one.  When you are finished with this tutorial, your application will look something like this:

In this section, I will not only teach you how to display the SQL data in UITablewView, but I will be detailing how to display it in multiple columns with images and text.  For this tutorial, you will need to download the following images.

We will be using these images to denote the priority (Green = low, Yellow = medium, Red = high).

Bring Your Code Up To Speed

Before we begin, we need to add some code to the Todo.h and Todo.m class to support the priority field in the database.  Open up Todo.h and add the following code:

All that is new here is the added NSInteger priority property.  We will be using this to get and set the priority for a given todo object.  Next, open Todo.m and add the following code.

The first line that has changed is the synthesize line.  We added our priority property to allow XCode to create the getter and setter methods for it.  Next, you will notice that the sql statement has changed slightly.  We are now getting the priority in addition to the text from the todo table.  Finally,  we set self.priority property to the selected priority value from the todo table.  This is done by using the sqlite3_column_int method.  We pass the init_statement and the number 1.  1 being the index of the sql array for which the priority data is contained.

Add Images to Your Project

Download the images above and save them to your project directory.  Inside of your project, right click (control-click) on the Resources folder and click Add -> Existing Files… Browser for the images, select all of them and click Add. Check the box that sais “Copy items into destination group’s folder (if needed)”.  Click Add. The image files should now appear inside of your Resources folder.

Create a UITableViewCell Subclass

To display data in columns within a UITableView, we have to create our own cell class that defines the type of data we want to display.  By default, Apple provides us with a simple cell object that can only display one column of text.  Normally, this is fine as it will work for a wide variety of applications.  Since we require 3 columns for this tutorial, we need to wrap our own cell object.

Click File -> New File… and select UITableViewCell. Click Next.

Name this file TodoCell and make sure this that the box that sais “Also create TodoCell.h” is checked.

This will create a “barebones” UITableViewCell object with some basic methods already filled out.  Let’s add some properties to this class.  Open up TodoCell.h and add the following code.

Let’s take this line by line…

First, we see a Todo object being declared.  Each cell will know which Todo item is associated with it.  This will help out when updating the data in each cell.  Next, we see 2 UILabels and a UIImageView.  To understand why these components are needed, here is a screenshot of how each cell will look.

We see the “Green Dot” which is an image being rendered by a UIImageView.  The word “low” and “Take out the trash” are both UILabels. After they are declared, we simply create them as properties.  Notice that we are NOT creating a property for the Todo object. We will not be synthesizing it either. This is because we want this variable to be private.  Setting this variable requires some additional code so we don’t want any code writer to simply be able to say cell.todo = foo;  You will see why this is so further on in this tutorial.

Below this are some method declarations.  First we see the method “imageForPriority”.  We will be using this method to decide which image (green, red, yellow) gets displayed for a given priority.  Next, we see the “getter and setter” methods for the todo object.  As I explained above, the setter will contain additonal code besides assigning the todo object.

Now open up TodoCell.m.  We will be writing quite a bit of code in here so I will break it up the best I can.  First, add the following code to create some of the initialization:

Ok, some new stuff here.  First, we see 3 static UIImages.  These will hold reference to each of the three images (red, green, yellow).  Since we only need to allocate them once, we make them static.  Static means that they will be associated with the class not the instance.  So we can make as many TodoCells as we want but only 3 UIImages will be created.  On the next line there is a private interface.  This allows us to declare a private method that no one else can use except this class.  Following this is the synthesize line.  Notice again that we are NOT synthesizing the todo object.

Looking at the initialize method…  All that is going on here is we are intanciating each of our UIImages with the correct image for a given priority.  This initialize method will get called once when the first instance of the todocell class is built.  Moving on… Add the following code: (Note: it might be small and hard to read.  If this is the case, click on the image to open it and the text will be full size)

This is the initialiazation method for any UITableViewCell.  First, we need to call the super classe’s (UITableViewCell) initWithFrame to ensure that the underlying components of the cell get set up properly.  Next, we get a reference to the contentView.  The contentView is the view for each cell.  We will be adding all of our UI components to this view.

The next 3 lines initialize a UIImageView and add it to our view.  Notice that we are populating it with the priority1Image.  This will just be a dummy placeholder until we update it.

Following this, we initialize the todoTextLabel.  This label will display what it is we need “to do” such as “Take out the trash”.  There is a method that we will be calling called “newLabelWithPrimaryColor”.  This is a method I will detail a little further down.  What it will do is build a new label with the attributes that we specify when we call it.  This method was taken directly from Apple’s “Seismic XML” sample code.  It’s pretty handy.  After this gets called, we simply add the new label to our view and these steps get repeated for the todoPriorityLabel.

Finally, the method “bringSubviewToFront” is called on the priority UIImageView.  This method is used in case there is text that gets near the image.  It will cause the image to appear above the text.  You can use this for layering your UI components.

Still with me?  Good… now let’s add the following “getter” and “setter” methods for the todo object.

The first method todo is simple.  All it does is return our todo object.  The setTodo is a little more involved…

First, we set the incoming (newTodo) to our classe’s todo object.  Next, we update the UITextLabel so we can display the detailed todo information.  Following this we set the image of our UIImageView by calling the method imageforPriority.  I will detail this method further down in this tutorial but all it does is return an image for a given priority.  Last, we have a switch statement.  The syntax of a switch statement is the same in objective C as it is in most languages.  If you don’t know what a switch statement is Google it.  Based on the priority of the newTodo, the priority label gets updated with one of three words (High, Medium, Low).  The [self setNeedsDisplay] tells the cell to redisplay itself after this todo has been set.

Now, let’s add the code that lays out the cell.

This method gets called automatically when a UITableViewCell is being displayed.  It tells the UITableView how to display your cell.  The define statements are similar to define statements in C.  The reason we are coding like this is because we can tweak these variables to get the display to our liking.  First, we call the layoutSubviews of the super class.  Next, we get a reference to the contentView.bounds.  This variable will allow us to figure out how much drawing area we have and allow us to line objects up properly.

The if(!self.editing) part is not neccessary but is good practice.  You would use this if you allowed editing of your cells.  This code is a little tough to explain by typing, but I will do the best that I can.  First, we declare our right-most column.  This is done by making a frame to hold the content.  This column will hold the text of the todo item.  Most of the code here is just positioning.  You can play with these numbers and see how it moves stuff around.  Once all of the positioning code is completed, the frame of our todoTextLabel gets set to this newly created frame.  This is done for each of our UI components.  You can lay them out however you like, as I may not have the best layout.

We have one more method to override.  It’s the setSelected method.  Go ahead and add the following code.

This method gets called when the user taps on a given cell.  We need to tell the cell how to behave when it gets tapped on.  This method should look pretty straight forward.  First, we call the setSelected method of the super class.  Next, we update the background color depending on whether or not the cell was selected.  Finally, the labels get set to a white color if the cell gets selected.  This is to contrast the blue color that the background becomes when the cell is selected.

This last 2 methods that I want to talk about are the helper methods that we used earlier in the code.  Add the following methods to your code.

newLabelWithPrimaryColor

This method got called when we were initializing our UILabels.  It takes a few parameters that should be pretty self explanatory.  Looking through the code, we first see the font being initialized with the size that we specified.  If bold was specified this is also accounted for.  Next, we instantiate a new UILabel and give it some properties.  Finally, this newly created UILabel gets returned.

imageForPriority

This method is actually quite simple.  It simply takes a priority and returns the UIImage that is associated with that priority.  Notice the default clause.  I decided to handle it like this instead of doing “case 1″ to handle all other cases.  For whatever reason, if there is ever a priority that is not 1,2 or 3 it will, by default, have low priority.

Now that we have created our UITableViewCell, we need to display it in the table.  Open up RootViewController.m and add the following import statement.  This will allow us to use our TodoCell object.

Now find the numberOfRowsInSection method and add the following code

I’m not going to really go over this, as this is almost the exact same code as in the Fruits example.  Basically, we are returning the number of todo items.

Now for the magic…We will now add our TodoCell to allow it to be displayed.  Find the cellForRowAtIndexPath method and add the following code.

This code is fairly similar to the default code that Apple has provided us.  The first change is we are instantiating our TodoCell object.  We are creating it with the initWithFrame method and passing our identifier to it.  Next, we get reference to the application’s appDelegate and use it to look up the todo item at the given index.  This should be familiar.  Finally, we set the todo item of the cell to the todo item at the row index and return the cell.  That’s it! Go ahead and click the Build and Go icon and see your todo list come to life.  Here is a screenshot of what your app should look like.

That concludes part 2 of this tutorial. Join me next time as I show you how to display detailed todo info using some new UI controls that we haven’t seen yet. As always, post your questions and comments in the comments section of the blog. Download The Sample Code

Happy iCoding!

  • Per@

    Thnx for this great tutorial :)

  • danny

    Thanks for the tutorial.

    FYI: The source is missing the icon.png so it doesn’t compile

  • http://www.icodeblog.com Brandon

    hmm that’s odd, thanks for the heads up

  • john

    THANKS, looking forward to working through this!!!

  • Elliot

    Hey thanks for the tutorials they’ve been a big help in learning to use the iPhone sdk. Just a question will the final todo list write back to the database??

    also incase you wanted to know “command + shift + 4 + space” lets you choose which window to screen shot saves you having to crop them etc

    -Elliot

  • John

    Hi Brandon,

    Could you post a link to the source code again. I’m getting an error:

    2008-09-03 11:54:34.916 todo[1676:20b] size:DIGG this tutorial
    2008-09-03 11:54:34.923 todo[1676:20b] *** -[UIImage initWithImage:]: unrecognized selector sent to instance 0x457df0

    and just want to compare the code.

    Thanks,
    -john

  • http://www.icodeblog.com Brandon

    @elliot

    Yes in one of the coming parts of the tutorial we will be writing to as well as deleting from the database.

    @john

    I will be reposting the source soon

  • yali

    Nice tutorial. Great job, Brandon. thanks. When will the part 3 and part 4 be available ?
    we can’t do anything with it right now. I am looking forward to the upcomming parts of the tutorial. Thanks.

  • Sam

    Whens tutorial 3?

    and when will u be able to add to do’s?

  • http://www.icodeblog.com Brandon

    Its in the works… 18 credit hours of senior level computer science classes doesn’t usually allow much free time.

  • Sam

    i see. take your time i just would like to know how to add to do’s

  • Doug

    Thanks for the great tutorials! I’m stuck on this one – it’s opening in the simulator with nothing in the list. Possibly doesn’t see any entries in the database? I created the todo.sqlite database and it’s in my project – I’m not sure how to diagnose the problem.

  • http://www.icodeblog.com Brandon

    I posted the sample code. Try downloading it and comparing it to yours.

    Open the console and post the error message you are getting. It’s probably some simple type-o. That always happens to me.

  • Nettuno

    Great tutorial, could you leave the source code (second part) to understand all the project!?
    Many thanks for all cooperation.

  • Anders

    fantastic! keep up the goodwork!!

  • Nettuno

    Ok sorry but yesterday I cannot found it.

  • http://blog.keegan3d.com Dave

    I have been trying to figure out how to use Interface Builder with a table cell, any chance you know how to do this and if so could it be added to the tutorial?

    Even without it this is an awesome tutorial series, cant wait for the next installments!!

  • arod

    Brandon, thank you so much for these tutorials, I was finding it difficult to separate the SQLite stuff from the rest of the code in the SQLiteBooks demo. When I created the db in the terminal, I noticed that ‘pk’ have no values. I manually added them in a SQLite manager. Should SQLite be autoincrementing “pk”? Thanks again.

  • arod

    John, I had a very similar error when I was building the app. Mine compiled but would not build. Turned out I had used “UIIMage” instead of the required “UIImageView” when allocating todoPriorityImageView.

    Its in the TodoCell.m file: self.todoPriorityImageView = [[UIImageView alloc] initWithImage:priority1Image];

    May not be the cause but perhaps you have the same typo….

  • http://www.icodeblog.com Brandon

    @arod,

    pk should auto-increment. This is one of the nice features of the PRIMARY KEY data type.

    I wander why it’s not doing this for you…

  • arod

    Perhaps the SQL manager that I’m using doesn’t display them. According to this, http://www.sqlite.org/autoinc.html, it should be autoincrementing. I guess I’ll find out when we continue with the tutorials. Thanks Brandon.

  • arod

    Brandon, The SQLite engine autoincrements fine. The problem was that I defined the pk as type “INTEEGER”. Duh. Also, my SQLite GUI manager shows the “pk” value as blank because it’s actually an alias to the ROWID. That’s what made me think there was a problem. Sorry about that.

  • 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 2 [...]

  • Christian

    Hey,
    Great tutorials, hoping from your blog I’ll learn all I need to know to start coding on my own. I’ve never written Obj-C before, actually done very little C! Furthest I ever ventured out into the wide world of coding was A bit of Delphi (Obj-Pascal) and Lua.

    Anyway, I’m getting a really weird error. I’ve checked my code over, but when I try and build, there’s an error in
    #import “TodoCell.h”
    that says “Error: Todo.h: No such file or directory”
    Makes no sense to me, Todo.h does exist!!!

    Any help would be much appreciated, I’m still getting around 30 errors on build and the majority of them are down to this I think.

  • http://www.icodeblog.com Brandon

    That is strange. This error is occurring in TodoCell.h? So you completed the previous tutorial (part 1) with no errors?

    Let me know. Also, have you tried comparing your code to the sample I have provided for download. I’m sure it’s something simple you may be overlooking.

  • Willem

    Christian,

    I had the same type of errors; mentioning missing import files (which did exist) and throwing lots of errors over a single type-o.

    Turned out I made a mistake in including my files; I had written

    #import

    Where I had to write

    #import “SQLToDo.h”

    Check your brackets / quotes in your imports, maybe that will solve it for you.

    Brandon, great tutorial! Gives a lot of insight. I think you’re doing a great job; the tutorials are not too long but go in-depth enough and taught me a lot in only a few hours time. Keep up the good work!

  • Willem

    Mhm, something went wrong interpreting the source code in my previous post (Brandon, maybe you can replace special characters in posted message by their respective HTML entities?). What I meant was:

    I had written
    #import <SQLToDo.h&rt;
    Where I had to write
    #import “SQLToDo.h”

  • Willem

    And now for the final version (sorry):

    I had written
    #import <SQLToDo.h>
    Where I had to write
    #import “SQLToDo.h”

  • http://www.satosoft.com geordie_git

    Brandon,

    Yet another great tutorial!!

    I’ve come from a VB.Net background and have only done that from time to time, so I’m not a hard core programmer by any stretch, more of an enthusiastic amateur!

    Thanks for this, I look forward to your other tutorials. :-)

    Cheers

    Graham

  • Ricco831

    This is an awesome tutorial. I have been looking for a SQL Lite tutorial for the longest time. I actually found this site on http://www.iphonedevver.com which is an iPhone SDK tutorial search site.

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

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

  • DEJO

    Just a note that the priority images are downloaded as red1.png, green1.png, and yellow1.png but referenced in the code as red.png, green.png and yellow.png. They should be renamed either before being added to the project or in the code.

  • http://www.icodeblog.com Brandon

    @Dejo,

    Thanks for the heads up. This tutorial has been up for a while and I can’t believe not a single person has pointed that out until now. I went ahead and fixed the image names so they should be correct now.

  • Bolinoid

    Great tutorial. Having no experience with Objective C or SQL Lite, it has been a huge help. I am having one problem though. I compile with no errors, and the db opens, but the if condition in todoAppDelegate, if(sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) never resolves to true, so I never get any data displaying in the table. Any ideas why?

    Thanks.

  • rksaraf

    so I went through the first part no problem. This second part, however, after i fixed all my naming errors and ran it in the simulator, all i got was a blank tableview. I checked my sqlite file to see if it had content, and it does. I then ran your code, that I downloaded, and it worked fine, so I tried replacing the todo.sqlite files to see if yours would work in mine and mine would work in yours. It didn’t, so I was left confused, but switched the files back, and now your code crashes when i run it..annd mine still doesn’t work…ideas? anything you can to do help.

    thanks

  • http://www.brackeen.net brian

    @DOUG:

    I had the same problem, if forgot to add:

    [self createEditableCopyOfDatabaseIfNeeded];
    [self initializeDatabase];

    to: applicationDidFinishLaunching in the appdelegate.m

    Once I did that it fired right up!!

    Thanks for the great tutorial!!!!

  • kappolo

    Hi all and thanks for those very helpful tutorials! :)

    Well, i have a problem. I used IB to build a view that has three objects: two buttons and a UITableView.

    The problem is that i can’t use the table view in the code: even if i declare it in IB as “myTableView” class and i create the myTableView.m and .h in XCode methods like

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

    implemented there are never called in the program (even if the table view is correctly viewed and the container view has is right file’s owner).

    What am i doing wrong?

    Thanks in advance :)

  • Lakario

    Is there any particular reason you’re defining

    -(Todo *)todo {
    return self.todo;
    }

    This is a cyclical definition that will never actually work because it simply calls back on itself.

  • http://www.icodeblog.com Brandon

    @ Lakario

    Good question…This is the syntax for writing the “Getter method” for the todo object. Since we don’t require any special functionality, we just return the todo object.

    It is necessary because we are not synthesizing the todo object.

    I hope that clears it up for you.

  • http://www.mercurytechnologies.co.uk Mark

    Hey,

    Awesome tutorials, so thanks very much for that. I still don’t get this code 100% so I can’t decide why something isn’t working… and I wondered if you might be able to give me a clue.

    My app compiles with no errors, but when I run it, only the top row comes out as expected, all other rows just come up blank with a red icon (i.e. the red.png) no matter what text/priority I have them set to in the database… I have checked the database and it seems fine.

    Thanks,

    Mark

  • http://www.mercurytechnologies.co.uk Mark

    I had a } out of place!

    DOH!

  • Ron

    Hi Brandon,

    Thanks for the great Tutorials. I have learned so much. I have a question about a warning that I am getting that is keeping the program from launching properly. I am getting a warning that says “warning: no ‘initWithFrame:reusableIdentifier:’ method found”

    it is in regards to this line of code : cell = [[[TodoCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];

    I downloaded the source you provided and got the same warning. Any suggestions?

    Thanks for your help!

  • Ron

    i actually got the program to launch by changing “MyIdentifier” to MyID” but now I am having an issue where none of the info I added to the database is being displayed in the app. I have been going through and adding comments to the log to see where the issue is and I think it somewhere around the ‘initializeDatabase’ function. I still can get the source code you added to run properly. Its telling me is quit due to an uncaught exception.

  • John B.

    Great tutorial, this is a huge help.

    I finally got the code to compile without errors and warnings, but it won’t run and I can’t figure out why.

    By stepping through I see that it gets to the line in RootViewController.m:

    [cell setTodo:td];

    The debugger has error: “TERMINATING_DUE_TO_UNCAUGHT_EXCEPTION”.

    The stack trace is pretty much meaningless.

    I put breakpoints in every possible function in “TodoCell.m” but none of them are hit. I can’t step into that function call, if in fact that is a function call.

    What does that statement do? I still can’t get used to this crazy square bracket syntax.

  • Narender

    I tried this one but only priority images are published, i debugged it and found that data is coming , assigning to labels but only images are visible, no label is visible, i found that layoutSubview is not getting called. can you help me please.

  • narendar

    Ok , i got rid of it, it was my mistake , layoutSubView i was writing instead of layoutSubviews that is why it was not getting called and i was unable to saw the text. now it is working perfect. thanks for such a good tutorial.

  • Mike

    How do you make the priority Image bigger?

  • http://www.freshapps.com Brandon

    Put a larger image and make the cell height larger….

  • bigcheese

    HI,
    could you provide the steps to create a index on the right hand side of the tableview?
    (like in the adress book, a-z)
    perhaps not so usefull for the todo-list, but here you showed us how to make a custom cell, perhaps it has to do with it?

    I love your tutorials …
    thanks,
    bigcheese

  • http://dnfinder.com Joe

    Hey I am curious, is there any way to compare files against your versions line for line (similar to subversion). I have a weird error where the program compiles launches and immediately quits.

    Apple returns this useful info.

    Process: todo [33841]
    Path: /Users/(myname)/Library/Application Support/iPhone Simulator/User/Applications/FA61925A-C158-4661-BFCE-3E5A1D42833D/todo.app/todo
    Identifier: todo
    Version: ??? (???)
    Code Type: X86 (Native)
    Parent Process: launchd [91]

    Date/Time: 2009-01-08 06:59:15.573 -0800
    OS Version: Mac OS X 10.5.5 (9F33)
    Report Version: 6

    Exception Type: EXC_BREAKPOINT (SIGTRAP)
    Exception Codes: 0×0000000000000002, 0×0000000000000000
    Crashed Thread: 0

    Application Specific Information:
    iPhone Simulator 1.0 (70), iPhone OS 2.0 (5A345)
    *** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘*** -[TodoCell newLabelWithPrimaryColor:selectedColor:fontsize:bold:]: unrecognized selector sent to instance 0x458f20′

    There is more info, but apparently something I did wrong with the newLabelPrimaryColor: method, any ideas where to look to fix this?

  • http://dnfinder.com Joe

    I figured it out, after carefully examining your code, the problem was mine (of course) =). It was a capitalization issue, the newLabelWithPrimaryColor function had fontsize instead of fontSize with a capital S in declaration and where being called, so it created that weird situation, seems to work now.

    I’m not sure why the compiler even worked if this was the case. Are there ways to protect myself from these kind of errors in the future (took me an hour to figure this out).

    Thanks in advance and look forward to your guidance =).

  • Ben

    I have noticed a lot of people (including myself) having problems with capitalization, misspelling, and syntax. I am new to XCode, so I’m not used to the debugger. Is there a way when there isn’t an explicit error, but rather an exception thrown, to locate that error with the debugger without going line by line?

  • http://www.sentinelbd.com Redwan

    Hi Brandon,

    Your example worked fine. But,I am trying to crate a to-do list with 5 items instead of 3.

    When I debug the line

    if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK)

    it doesn’t get inside the code block under “If” statement.

    Can you show me some light?

    Redwan

  • http://www.sentinelbd.com Redwan

    Brandon,

    The file was todoAppDelegate.m file.

    Redwan

  • http://www.vsplash.com kavita

    Hi Brandon,
    Very nice tutorials.
    I am very new….
    I have the same code as you have said…
    Its compiling good
    but in the simulator data is not appearing
    Please could you help me to fix it.
    What i should do to get the data in the simulator

    thanks in advance
    bye
    kavita

  • http://www.vsplash.com kavita

    sorry my mail address is wrong it is adjusted again

    bye
    kavita

  • wiegeabo

    Brandon,

    Great tutorials. I’ve got the todo app running, but no images are showing up. Just the data. And I haven’t found any differences with my code. Any ideas?

  • wiegeabo

    @kavita

    I has the same problem. Then I noticed that I had named the function layoutSubview instead of layoutSubviews.

  • http://www.foldifoldi.com vii

    When I try to run the supplied sample code, my simulator crashes while Xcode displays this message:

    “TERMINATING_DUE_TO_UNCAUGHT_EXCEPTION”

    It looks like others have had this problem. Any ideas?

    Thanks.

  • http://sebastien-arbogast.com Sebastien Arbogast

    I’m a little disturbed by your private interfaces. I’m just learning Objective-C and I thought private methods could just be declared in the header file but in a @private section. Am I right to assume that it has the same effect as your private interfaces, without hiding those methods from people importing header files?

  • maxfiresolutions

    Hi,

    These are really great tutorials for first timers like me to MAC and iphone development in particular. Bravo!

    I just want to ask one question…. which is off course silly. Why havnt you declared @ property (nonatomic, retain) sqlite3 *database or something similar in the todo.h file.

  • http://afruj.wordpress.com/2009/03/24/iphone-tutorials/ iPhone development Tutorials « The Brook Song – ঝর্ণার গান

    [...] 49. TodoList sqlite 2 [...]

  • LakshmiKanth Reddy

    Hi Brandon,

    You are really doing a superb job, which cannot be expressed, with your work many people like me are able to gain the knowledge, here i have one query :

    if i want to create an application where the horizontal and vertical scrolling of the application has to be done based on the device movement, ie., if we move the device to left then it has to do the left horizontal scrolling and if towards right then right horizontal scrolling and same for top and bottom .

    ie., we have to do the coding based upon the system events, can u help me out in doing this.

    if anybody can help me out in this then it would be greatly appreciable.

    Thank you .

  • Wilbert

    Hi,
    Your tutorials are very helpful. I’m new into iphone programming and having found your site was very useful in my development.

    I followed your todo example but modified it a bit, instead of using an sql to retrieve the data, i used an array just like in the fruits example. however, im am getting an error “_TERMINATING_DUE_TO_UNCAUGHT_EXCEPTION___”. Also, there’s a warning on the property for the three todoCell data (todoTextLabel..), “requires method setTodoTextLabel to be defined – use @synthesize, @dynamic or provide a method” though I synthesize it as describe in your tutorial.

    Could you please provide me some code on how to do this using array instead of accessing the database?

    thanks,
    Wilbert

  • http://N/A ColeBucket06

    My source compiles with no errors, warnings, etc; however, when it compiles I am left with a blank UITableView as was ‘rksaraf’. Any incite on this issue? I double checked my code and it seems to all be correct. The only thing I did was change a few things as I am trying to create a Task Manager app that will eventually call a database via server, populate the UITableView, then allow for responses back to the host server; however, if I can’t get this working I guess I’m S.O.L. Could someone please assist me on this issue?

  • 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)
    replace
    “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;
    else
    self.text = [NSString stringWithUTF8String: pointer];”

  • Calgman

    Hi – This is a great tutorial for us beginners. Thank you very much for taking time to develop this series.

    I like to work thru problems. Having said that, I approached this tutorial w/ a twist of using my own variables rather than what the tutorial used – that way, I have to work to fix the compile/run-time errors.

    I called the database sql_todo.sqlite, but used the same table name as in the tutorial (todo) when populating it; but in the code I used sql_todo for the “select” statement. Because of this, no data was shown in the simulator. After I fixed the code, the simulator shows data – but the format is not what the tutorial shows.

    1. The priority label is on the right side (over-writes the text of the to-do list)
    2. The priority images are not shown at all.

    I have checked the code and the #defines in the layoutSubviews() method. I am still scratching my head.

    Any pinters? Thx in advance!
    Calgman

  • Anurag

    @rksaraf I had the same problem with only the priority images showing up. I named the function wrong. It was supposed to be “layoutSubviews” but I called it “layoutSubViews” with a caps V. I’m so glad that things are case-sensitive in Obj-C :)

    Thanks for the awesome tutorial Brandon.

  • garyZ

    Thanks for the SQL parts of the tutorial. I have used it to load tables and store information when I start using handleOpenURL. I didn’t create the project as a Navigation Controller and had to add the RootViewController class and the RootViewController.xib. Using your example to set the IB outlets I believe I have them setup correctly. However the screen displays only “Root View Controller” at the top and an empty window. Is there anything I might be missing in the Interface Builder.

  • garyZ

    Brandon,

    I want to thank you again for these wonderful tutorials. After much pain and time attempting to add a navigation controller to my existing project I decided to start with a new project and one of your earlier tutorials. I will then add my existing code to it. Once again thanks as I have read many of Apple’s sample projects and it is your screen shots and how to use Xcode and Interface Builder that makes any of their code useful.

    Gary

  • Claijon

    Who am I? Where am I?
    totally lost…

  • Kl

    Hi Brandon,

    I have a “_TERMINATING_DUE_TO_UNCAUGHT_EXCEPTION_” error when it reaches the line ” [cell setTodo:td]; ”
    not sure what is wrong.

    Thanks,
    KL

  • mora
  • http://www.aplacebetweenhere.net Daniel

    Could you update it to SDK 3 ? I got problems at the “magic” at the to last step (cellForRowAtIndexpath & numberOfRowsInSection) since of the new naming of appdelegates, tried to go through the apple provided book exmaple, but that didn’t work.
    Great tutorial btw :)

  • Robert

    I had to add #import “todoAppDelegate.h” to the RootViewController.m to get it to compile and that just doesn’t seem right to me.

    Am I missing something?

  • http://www.callcontext.com Geoff

    I’m also getting the uncaught exception issue. The problem appears (for me) when the sqlite3_prepare_v2 call is made in the initialiseDatabase call in TodoAppDelegate.m. I added an extra check for the result of the call and logged an assert with the message reported from SQLite. The message is “library routine called out of sequence”.

    If I run your sample code, it works no problems. So my guess is it’s something to do with the SDK version of either the iPhone or SQLite. I checked the reference for SQLite, and we’re both pointing to libsqlite3.0.dylib.

    When I highlight the library reference and click the info button in the toolbar, I see that your library path is the same as mine (usr/lib/sqlite3.0.dylib), but the full path is different. Your path is rooted in my downloads directory under the downloaded project directory name, then iphoneos2.0/usr/lib/sqlite3.0.dylib, and mine is rooted in developer/platforms/iphoneos.platform/developersdks/iphoneos3.1.2.sdk/usr/lib/libsqlite3.0.dylib.

    I have the downloaded code set to compile against simulator 3.1.2; the same as my follow-along project, however the reference appears to be against a different version of the library. I would expect if we’re compiling against the same version of the SQLite library, that the API wouldn’t have changed, but that’s the only thing I can thing of – that there’s a missing call before the prepare in the version of the library I’m working against?

    I’m new to the Mac, and iPhone programming. I hope this can be useful to yourself or one of your readers. I’ll keep digging in the meantime, and post if I find an answer first.

    Thanks for the great tutorials. They’re easy to follow and quite informative.

  • http://www.robincrama.nl Robin

    @Robert

    I had the same problem, Txs for the solution. I got the next error in RootViewController.m

    Error: todoAppDelegate undeclared (first use in this function)
    error: appDelegate undeclared(first use in this function)
    error: expected expression before ) token

    with Finally, the method it was solved:)

  • IISword

    Yo I couldn’t get the program to initialize the three images in the beginning without calling the method in one of my other cell. Any ideas on what happened? (and yes I did use a +)

  • IISword

    nvm I didn’t spell initialize right

  • http://www.warriorforum.com/blogs/rayray7/8778-history-ways-avoid-nigerian-419-scam.html Felipa Wentling

    Your post is an inspiration for me to discover more about this topic. I must concede your lucidity expanded my sentiments and I will forthwith grab your rss feed to remain up to date on any succeeding articles you might write. You are due, thanks for a job well done!

  • http://zdavatz.wordpress.com Zeno Davatz

    My code compiles but then crashes after install on the iPhone-Simulator. That must be a memory leak but how do I find that memory leak?

    I also get No -’initWithPrimaryKey:database:’ method found.

    But as said: it still compiles and installs. Then it just crashes on the Simulator.

  • http://zdavatz.wordpress.com Zeno Davatz

    Ok, this is what GDB tells me:

    Attaching to process 10936.
    2009-12-23 10:32:39.211 todo[10936:207] *** +[UIFont boldSystemFontOfSize]: unrecognized selector sent to class 0x16927e0
    2009-12-23 10:32:39.213 todo[10936:207] *** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘*** +[UIFont boldSystemFontOfSize]: unrecognized selector sent to class 0x16927e0′
    2009-12-23 10:32:39.214 todo[10936:207] Stack: (

    I am on Xcode 3.2.1

  • http://zdavatz.wordpress.com Zeno Davatz

    Ok, was missing the :fontSize in

    UIFont boldSystemFontOfSize:fontSize

    Console Debugging is very useful!

  • http://zdavatz.wordpress.com Zeno Davatz

    See: http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UITableViewCell_Class/DeprecationAppendix/AppendixADeprecatedAPI.html

    initWithFrame:reuseIdentifier:

    Initializes and returns a table cell object. (Deprecated in iPhone OS 3.0. Use initWithStyle:reuseIdentifier: instead.)

    That is in file TodoCell.m:32

    How do I need to change that?

  • http://zdavatz.wordpress.com Zeno Davatz

    Ok, above is not necessary. I mixed up

    todoPriorityLabel

    with

    todoTextLabel

  • Kevin

    In TodoCell.h in your solution I am getting three errors:

    The errors are:
    error: expected specifier-qualifier-list before ‘Todo’ (line 13: Todo *todo;)
    error: expected ‘)’ before ‘Todo’ (line 25: -(Todo *)todo;)
    error: expected ‘)’ before ‘Todo’ (line 26: -(void)setTodo:(Todo *)newTodo;)

    Can anyone help? I am using the code sample code from this site, so I don’t understand what could be wrong. Thanks

  • http://www.teknotica.co.uk Silvia Rebelo

    Hi Brandom,

    I’ve been following your tutorials and all have been really useful. Thanks a lot for sharing them.

    I’m having issues with this particular one: has no errors but doesn’t display anything…

    I download then your code. I run it and… same thing.

    Have you got any idea what is this happening?

    Thanks in advance.

  • MIke

    I have same problem with Silvia

  • MIke

    I finde why there is empty list, for some reason by me, the database path have to user absolute path. That means in file: todoAppDeleagate.m and funcion name: initialzeDatabase, you have to difine your database path.

    Yes, NSLog() will help you. for using that, you have to write

    #define DEBUG

    after import part by file todoAppDelegate.h

    Hope my infomation could help somebody.

  • Campbell

    Hey great tutorials.

    I’m getting a compile error in RootViewController.m – “TodoCell” undeclared.

    Everything compiled just fine until this point.

    “Todo.h” and “TodoCell.h” have both been included.

    Any thoughts?

  • Campbell

    Never mind found it. I named the class ToDoCell.

    You always find your errors after you ask the question.

  • pithhelmet

    Hi Brandon….

    Three questions -

    1) How do I add a login page to be first page displayed on this application? Just a simple view with a graphic, a text entry field and a button. The button click will bring up the tutorial entry point?

    2) When the item list is first displayed, the icons and priority are correct (as in database) but when I look at item, change priority, then return to item list, the icons for the priority are all green dots?

    3) When I deploy the application to my iTouch, if i leave the debug code section in, the app works… if I set it to release, the app will not show the detail view of the data.

    Thanks for a fantastic tutorial!!

    take care
    tony

  • pithhelmet

    One additional question….

    the update status button text does not change when clicked. I know the event is being fired because the text in the status text line does indicate the proper values, just the toggling of the button text does not work….

    any ideas?

  • Ham

    Great tutorials. Couple notes for Xcode 3.2.2 users…
    RootViewController.m should end up with the following imports. The part 1 and 2 tutorials do not explicitly say to add all of these, and for me at least, Xcode did not auto add them, but they are present in the downloadable sample code.

    #import "RootViewController.h"
    #import "todoAppDelegate.h"
    #import "Todo.h"
    #import "TodoCell.h"

    Adding these resolved “appDelegate undeclared” errors.

    Also in TodoCell.m, “initWithFrame” is deprecated. The following update worked for me…

    - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
    // Initialization code

    UIView *myContentView = self.contentView;

    self.todoPriorityImageView = [[UIImageView alloc] initWithImage:priority1Image];
    [myContentView addSubview:self.todoPriorityImageView];
    [self.todoPriorityImageView release];

    self.todoTextLabel = [self newLabelWithPrimaryColor:[UIColor blackColor] selectedColor:[UIColor whiteColor] fontSize:14.0 bold:YES];
    self.todoTextLabel.textAlignment = UITextAlignmentLeft; // default
    [myContentView addSubview:self.todoTextLabel];
    [self.todoTextLabel release];

    self.todoPriorityLabel = [self newLabelWithPrimaryColor:[UIColor blackColor] selectedColor:[UIColor whiteColor] fontSize:10.0 bold:YES];
    self.todoPriorityLabel.textAlignment = UITextAlignmentRight; // default
    [myContentView addSubview:self.todoPriorityLabel];
    [self.todoPriorityLabel release];

    // Position the todoPriorityImageView above all of the other views so
    // it's not obscured. It's a transparent image, so any views
    // that overlap it will be visible.
    [myContentView bringSubviewToFront:self.todoPriorityImageView];
    }
    return self;
    }

  • http://www.iphones.co.il/forum/thread137089.html#post756406 Anonymous

    [...] [...]

  • Chaz

    Ham,
    Thanks for providing the updates. I was able to get it to build with no data showing, but once I updated with the code you provided everything loaded successfuly

  • Simon

    Hi, I follow your tutorial very carefully, and my app doesn’t open… When I put this code in comment
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    testAppDelegate *appDelegate = (testAppDelegate *)[[UIApplication sharedApplication] delegate];
    return appDelegate.todos.count;
    }
    my app open but nothing is show.

    Anybody have an idea?

  • Rakesh

    hi

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

    Good post again.

  • Rafik1982

    Hi I’m running the code on xcode 3.2.5, the application loads, but the data doesn’t.

    When I try to debug the appdelegate none of the breakpoints i place in the appdelegate are reached.

    It doesn’t load any of the todo items. Can someone help?

  • http://www.saverspoint.com/promotions.htm Special offers

    i think great post every one like it…

  • http://www.alm1ha.com/vb منتديات المها

    i think great post every one like it

  • CodeRefiner

    This program breaks the second you try to access the appDelegate the way you do so in your code.

    todoAppDelegate should be accessed differently when trying to access the todos array.

    Shame it was a good tutorial up until now.

  • CodeRefiner

    Scratch that, she works fine :)

  • CodeRefiner

    Scratch that, she works fine :)

  • CodeRefiner

    Scratch that, she works fine :)

  • SPatel

    I had to change the numberOfSectionsInTableView to return 1 instead of the array count.  I know that doesn’t make sense, but for some reason this method was being called multiple times (I’m guessing 5).  I haven’t worked out why yet.

    Anyway when I did that it all works fine.

  • SPatel

    I say 5 because I had 5 items in my database (not 4 as in the tutorial).

  • pvan1017

    Not sure why but I had to use stringByAppendingPathComponent instead of stringByAppendingFormat  in the createEditableCopyOfDatabaseIfNeeded method.

    p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #421b7c}

  • Freek Wielstra

    I have a few remarks about both this and part 1.

    First, it’s generally not recommended [citation needed] to spread SQL queries and data retrieval logic over the application: this tutorial indicates that retrieving the full list from the DB goes in the application delegate, and that retrieving of specific Todo model data goes into the Todo object itself.

    It’s generally considered better [citation needed] to move data access logic into a separate data access object. This keeps data retrieval and connection logic out of the application intitialization class.

    Second, there’s a few things turned deprecated since this tutorial was published. In particular, instead of the TableCell’s initWithFrame as indicated in this tutorial, one should override initWithStyle. The rest of the code remains pretty much the same though, nothing major to be changed.

    Finally, and this refers to the initial data retrieval indicated in the first part of the tutorial, you may want to add some error handling in case you accidentally make a typo in your SQL or whatever (like I did). Add an else to the ‘if (sqlite3_prepare_v2(/*blah*/) == SQLITE_OK)’:

            } else {            NSLog(@”%@”, [NSString stringWithUTF8String:sqlite3_errmsg(database)]);        }

    This’ll output the error message to the console if you run it from the iphone simulator.

    For the rest: It’s a lot of code (especially writing out the custom TableCell layout), but everyone has to have done something like that at least once.

  • http://onlinedolist.com on line to do list

    Great Article . Thank you.

    For the users who read this article,  Here is the Part 3

    http://icodeblog.com/2008/09/10/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-3/

    ———————
    online to do list
    http://onlinedolist.com

blog comments powered by Disqus