<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>iPhone Programming Tutorials &#187; SQLite</title>
	<atom:link href="/tag/sqlite/feed/" rel="self" type="application/rss+xml" />
	<link>http://icodeblog.com</link>
	<description>iPhone Programming Tutorials</description>
	<lastBuildDate>Tue, 19 Nov 2013 19:34:46 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=4.1.1</generator>
	<item>
		<title>Simple Sqlite Database Interaction Using FMDB</title>
		<link>http://icodeblog.com/2011/11/04/simple-sqlite-database-interaction-using-fmdb/</link>
		<comments>http://icodeblog.com/2011/11/04/simple-sqlite-database-interaction-using-fmdb/#comments</comments>
		<pubDate>Fri, 04 Nov 2011 19:52:19 +0000</pubDate>
		<dc:creator><![CDATA[brandontreb]]></dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[fmdb]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[SQLite]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=3595</guid>
		<description><![CDATA[Introduction
In the age where Core Data is king, the database that started it all is often overlooked. I&#8217;m talking of course about sqlite. As you may or may not know, prior to core data, sqlite was the preferred method of storing relational data on iOS devices.
Although, most developers don&#8217;t interact with sqlite directly, they still use it under the hood as the primary data store for core data. This is great and all, but there are often times when raw  ...]]></description>
				<content:encoded><![CDATA[<h4>Introduction</h4>
<p>In the age where Core Data is king, the database that started it all is often overlooked. I&#8217;m talking of course about sqlite. As you may or may not know, prior to core data, sqlite was the preferred method of storing relational data on iOS devices.</p>
<p>Although, most developers don&#8217;t interact with sqlite directly, they still use it under the hood as the primary data store for core data. This is great and all, but there are often times when raw sqlite is still the preferred storage method.</p>
<p>A few of these might include:</p>
<ul>
<li>Caching</li>
<li>Preferences</li>
<li>Simple objects</li>
<li>Portability</li>
<li>Cross platform applications</li>
</ul>
<p>Recently, I have had to make heave use of raw sqlite as a caching strategy in a new project that I&#8217;m working on. Being that we are developing a framework for other developers to include in their projects, we can&#8217;t always assume that they have their environment set up to use core data. When I was but a n00b iOS developer I did all of the crazy sqlite management by hand. See <a href="/2008/08/19/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-1/">This post series</a>, but don&#8217;t spend too much time there because it&#8217;s embarrassing.</p>
<p>Gross right? Now, there is a much easier way to manage and interact with your sqlite databases. This library has been around for quite some time and I wish I had known about it earyly on.</p>
<h4>FMDB</h4>
<p>FMDB stands for Flying Meat Database. What a great name&#8230; This project aims to be a fully featured wrapper for sqlite.</p>
<p>You can clone their repository on <a href="https://github.com/ccgus/fmdb">their github</a>.</p>
<p>This tutorial will give you a brief introduction to using FMDB to create a database, create a table, insert, fetch, and delete data.</p>
<h4>Project Set Up</h4>
<p>The first step is to download/clone fmdb from the url above. Once downloaded drag everything inside of the src folder into your project <strong>except</strong> fmdb.m. That file contains unit tests and a main, which will cause some conflicts in your project.</p>
<p>The next step is to link in the sqlite library. To do this:</p>
<ol>
<li>Click your project in the left column of XCode</li>
<li>Click the main target in the middle column. In our case it&#8217;s &#8220;FMDBTest&#8221;</li>
<li>Click the &#8220;Build Phases&#8221; tab in the third column</li>
<li>Expand the arrow next to &#8220;Link Binary With Libraries&#8221;</li>
<li>Click the &#8220;+&#8221; button</li>
<li>Search for libsqlite3.0.dylib and double click it</li>
</ol>
<p>When you are all done, it should look like this:</p>
<p><img title="" src="/wp-content/uploads/2011/11/Screen-Shot-2011-11-04-at-12.48.10-PM.png" alt="Screenshot" /></p>
<div style="clear: both;">
<p>Now, that we have the library in place, let&#8217;s write some code.</p>
<h4>Creating A Database</h4>
<p>Obviously <em>where</em> you create your database is up to you, but we are going to do it in the appDelegate.</p>
<p>In addition to working with existing databases, fmdb can <em>easily</em> create any number of databases for you on the fly. After importing FMDatabase.h in our AppDelegate.m file, we can add the following code to the <code>application:didFinishLaunching</code> method.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSArray</span> <span style="color: #002200;">*</span>paths <span style="color: #002200;">=</span> NSSearchPathForDirectoriesInDomains<span style="color: #002200;">&#40;</span>NSDocumentDirectory, NSUserDomainMask, <span style="color: #a61390;">YES</span><span style="color: #002200;">&#41;</span>;
<span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>docsPath <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>paths objectAtIndex<span style="color: #002200;">:</span><span style="color: #2400d9;">0</span><span style="color: #002200;">&#93;</span>;
<span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>path <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>docsPath stringByAppendingPathComponent<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;database.sqlite&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
FMDatabase <span style="color: #002200;">*</span>database <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>FMDatabase databaseWithPath<span style="color: #002200;">:</span>path<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>First, we resolve the path to the documents directory. Be careful, if you don&#8217;t <em>need</em> your database to be backed up, use the cache directory instead. When you send a path to the databaseWithPath method of fmdb, it first checks if the database exists, and if not, it creates it. Similarly, we could copy an existing database to the documents directory and source it the exact same way.</p>
<h4>Opening The Database And Creating Tables</h4>
<p>In order to perform any action on the database, it must first be opened. Here is the code to open the database and create a users table. Don&#8217;t worry about closing it right now, we will do that when we are all done.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#91;</span>database open<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>database executeUpdate<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;create table user(name text primary key, age int)&quot;</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>Here we first call the open method of the database to open it. Next, we use the executeUpdate method to create the table. Make sure you use this method and <strong>not</strong> executeQuery when creating a table. This is a common error. The database should look like this after our update:</p>
<p><img title="" src="/wp-content/uploads/2011/11/Screen-Shot-2011-11-04-at-1.05.12-PM.png" alt="Screenshot" width="550" /></p>
<div style="clear: both;">
<p>After we are all done here we close the database.</p>
<h4>Inserting And Deleting Data</h4>
<p>Inserting data using sqlite is very straight forward. You can either build your strings and pass them in directly OR use the sqlite format using &#8220;?&#8217;s&#8221; and letting fmdb do the work. Below is an example of each:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// Building the string ourself</span>
<span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>query <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> stringWithFormat<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;insert into user values ('%@', %d)&quot;</span>,
<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;brandontreb&quot;</span>, <span style="color: #2400d9;">25</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>database executeUpdate<span style="color: #002200;">:</span>query<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// Let fmdb do the work</span>
<span style="color: #002200;">&#91;</span>database executeUpdate<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;insert into user(name, age) values(?,?)&quot;</span>,
<span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;cruffenach&quot;</span>,<span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithInt<span style="color: #002200;">:</span><span style="color: #2400d9;">25</span><span style="color: #002200;">&#93;</span>,<span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>Generally, the second route is preferred as fmdb will do some of the sanitizing for your (such as add slashes to single quotes).</p>
<p>Now that we have some data in our database, let&#8217;s delete it. The following code will delete all users with an age of 25:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#91;</span>database executeUpdate<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;delete from user where age = 25&quot;</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>And that should remove both of the records that we inserted.</p>
<h4>Querying The Database</h4>
<p>Querying the database is a bit more tricky than inserting and deleting. FMDB has some great utility methods for helping us out in certain circumstances, but for this tutorial, we will assume the don&#8217;t exist and show you how to fetch data out. If you are following along in a sample application, put this code before your delete code (so that we actually have some data to work with).</p>
<p>Below is an example of fetching all users from the database:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;">FMResultSet <span style="color: #002200;">*</span>results <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>database executeQuery<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;select * from user&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #a61390;">while</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>results next<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>name <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>results stringForColumn<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;name&quot;</span><span style="color: #002200;">&#93;</span>;
    NSInteger age  <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>results intForColumn<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;age&quot;</span><span style="color: #002200;">&#93;</span>;        
    NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;User: %@ - %d&quot;</span>,name, age<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#91;</span>database close<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>We first query the database using the <code>executeQuery</code> method. This returns to us an FMResultsSet. Next we start a while loop that continues while there are results to be retrieved and fetch out each of our data points. Finally, we just print out each user.</p>
<p>And finally, our database gets close&#8230;</p>
<h4>Conclusion</h4>
<p>This concludes our sqlite using fmdb tutorial. As always, if you have any questions, please leave them here or <a href="http://twitter.com/brandontreb">write me on twitter</a>.</p>
<p>You can download the source for this tutorial <a href="/?attachment_id=3599">here</a></p>
<p>Happy iCoding!</p>
]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2011/11/04/simple-sqlite-database-interaction-using-fmdb/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>How To Integrate Google Analytics Tracking Into Your Apps In 7 Minutes</title>
		<link>http://icodeblog.com/2010/04/22/how-to-integrate-google-analytics-tracking-into-your-apps-in-7-minutes/</link>
		<comments>http://icodeblog.com/2010/04/22/how-to-integrate-google-analytics-tracking-into-your-apps-in-7-minutes/#comments</comments>
		<pubDate>Thu, 22 Apr 2010 15:02:06 +0000</pubDate>
		<dc:creator><![CDATA[brandontreb]]></dc:creator>
				<category><![CDATA[Snippets]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[google analytics]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[SQLite]]></category>
		<category><![CDATA[stats]]></category>
		<category><![CDATA[tracking]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=1906</guid>
		<description><![CDATA[So, why would you want to integrate Google Analytics into your iPhone application.  Duh, for the same reasons you would integrate it into your site.  Google has extended their killer analytics platform to include mobile devices including the iPhone and Android devices.

The analytics API gives you some very powerful options to get as nitty gritty as you would like in your application tracking.]]></description>
				<content:encoded><![CDATA[<p>Ok, maybe that title is +- 3 minutes depending on how efficient you are ;).</p>
<h4>What?</h4>
<p>So, why would you want to integrate Google Analytics into your iPhone application.  Duh, for the same reasons you would integrate it into your site.  Google has extended their killer analytics platform to include mobile devices including the iPhone and Android devices.</p>
<p>The analytics API gives you some very powerful options to get as nitty gritty as you would like in your application tracking.</p>
<h4>Why?</h4>
<p>Uhh, because stats are freakin sweet.  Even if you don&#8217;t have a million+ downloads of your app, it is still interesting to know how your users are using your application.  Being able to track every single action made by a user is priceless when thinking about the direction of your app including what features to add, improve, or scrap.</p>
<p>Imaging spending all of your time on some complex feature to find out that only 1% of your users even care about that feature.  How could you know that only 1% of your users actually care about that feature unless you are doing some sort of tracking.</p>
<p>So before you add that super duper all in one end all be all 1337 feature to your app, consider reading the rest of this tutorial and add stat tracking first.  It is quick and painless and I promise that it will be totally worth it.</p>
<h4>Configuring your Google Analytics Account</h4>
<p>Google Analytics is a free server provided by Google.  If you dont already have an account, you can sign up for one with your existing Gmail account.  <a href="http://google.com/analytics">http://google.com/analytics</a>. Sign up and log in.</p>
<p>The first thing you will want to do is Add a new <strong class="Apple-style-span" style="font-weight: bold;">Website Profile.</strong></p>
<p><strong class="Apple-style-span" style="font-weight: bold;"><a href="/wp-content/uploads/2010/04/Screen-shot-2010-04-06-at-10.45.36-AM1.png"><img class="alignnone size-full wp-image-1907" title="Screen shot 2010-04-06 at 10.45.36 AM" src="/wp-content/uploads/2010/04/Screen-shot-2010-04-06-at-10.45.36-AM1.png" alt="" width="386" height="71" /></a></strong></p>
<p>On the next page:</p>
<ul>
<li>Select Add a Profile for a new domain</li>
<li>Enter in <em class="Apple-style-span" style="font-style: italic;">some</em> URL &#8211; This doesn&#8217;t really matter since google doesn&#8217;t use it to identify your app.  A good convention is iphone.yoursite.com or appname.yoursite.com so that you know these stats are for your iPhone app.</li>
<li>Select your country and timezone</li>
<li>Click Finish</li>
</ul>
<p><a href="/wp-content/uploads/2010/04/Screen-shot-2010-04-06-at-10.47.20-AM1.png"><img class="alignnone size-full wp-image-1908" title="Screen shot 2010-04-06 at 10.47.20 AM" src="/wp-content/uploads/2010/04/Screen-shot-2010-04-06-at-10.47.20-AM1.png" alt="" width="689" height="395" /></a></p>
<p>Pretty simple&#8230; On the next screen, make sure you copy the <strong class="Apple-style-span" style="font-weight: bold;">Web Property ID</strong>. This number (begins with UA) is what we will be using to uniquely identify your application.</p>
<p><a href="/wp-content/uploads/2010/04/Screen-shot-2010-04-06-at-10.50.25-AM1.png"><img class="alignnone size-full wp-image-1909" title="Screen shot 2010-04-06 at 10.50.25 AM" src="/wp-content/uploads/2010/04/Screen-shot-2010-04-06-at-10.50.25-AM1.png" alt="" width="266" height="25" /></a></p>
<p>That&#8217;s all for the web side of things!  Now on to the iPhone part.</p>
<h4>Download the Google Analytics Library and Add It To Your Application</h4>
<p>This could not be easier.  Head on Over to <a href="http://code.google.com/apis/analytics/docs/tracking/mobileAppsTracking.html">http://code.google.com/apis/analytics/docs/tracking/mobileAppsTracking.html</a> . They explain much of the steps  so you could read the rest there, but I will lay them out in detail here with screesnhots.  Download the <a href="http://dl.google.com/gaformobileapps/GoogleAnalyticsIphone_0.7.tar.gz">Analytics SDK for iPhone</a> and extract it.</p>
<p>There are 2 files that are important.  Drag both files from the Library folder into your XCode project.  These files are GANTracker.h and libGoogleAnalytics.a.</p>
<p><a href="/wp-content/uploads/2010/04/Screen-shot-2010-04-22-at-7.29.49-AM1.png"><img class="alignnone size-full wp-image-1971" title="Screen shot 2010-04-22 at 7.29.49 AM" src="/wp-content/uploads/2010/04/Screen-shot-2010-04-22-at-7.29.49-AM1.png" alt="" width="397" height="70" /></a></p>
<p>When XCode pops up the confirmation box, make sure that you check the box that says &#8220;Copy items into destination group&#8217;s folder (if needed)&#8221;.  This will ensure that the code gets place in your project directory.</p>
<h4><strong class="Apple-style-span" style="font-weight: bold;">Include CFNetwork and Link Against the sqlite framework</strong></h4>
<p>The google analytics framework requires the use of CFNetwork (for interent connection detection) and the sqlite framework (most likely to store events when the user does not have internet).</p>
<p>Let&#8217;s start by adding CFNetwork to the project. Right click on the frameworks folder and select Add -&gt; Existing Frameworks.  Next, select CFNetwork.framework from the list and click Add.</p>
<p><a href="/wp-content/uploads/2010/04/Screen-shot-2010-04-22-at-8.07.14-AM1.png"><img class="alignnone size-full wp-image-1972" title="Screen shot 2010-04-22 at 8.07.14 AM" src="/wp-content/uploads/2010/04/Screen-shot-2010-04-22-at-8.07.14-AM1.png" alt="" width="352" height="548" /></a></p>
<p>Now we need to link the project against libsqlite3.0.dylib.  To do this Click Project -&gt; Edit Active Target &#8220;&lt;project name&gt;&#8221; where &lt;project name&gt; is the name of your XCode project.</p>
<p>Next, click the + button at the bottom to bring up the library picker. Select libsqlite3.0.dylib and click Add</p>
<p><a href="/wp-content/uploads/2010/04/Screen-shot-2010-04-22-at-8.11.23-AM1.png"><img class="alignnone size-full wp-image-1974" title="Screen shot 2010-04-22 at 8.11.23 AM" src="/wp-content/uploads/2010/04/Screen-shot-2010-04-22-at-8.11.23-AM1.png" alt="" width="510" height="442" /></a></p>
<h4>Including and Initializing the Tracker</h4>
<p>Since the Analytics tracker is a singleton class, we only have to initialize it once and the rest of the application can use the same instance.</p>
<p>Let&#8217;s start by opening up the app delegate and adding the code to import the Google Analytics framework.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;GANTracker.h&quot;</span></pre></td></tr></table></div>

<p>Now you need to initialize the tracker&#8230; Make sure you have the UA number handy that you received from Google earlier.  Add the following code to you applicationDidFinishLaunching method.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>GANTracker sharedTracker<span style="color: #002200;">&#93;</span> startTrackerWithAccountID<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;UA-15609865-3&quot;</span>
				dispatchPeriod<span style="color: #002200;">:</span><span style="color: #2400d9;">10</span>
				delegate<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>Make sure you replace my UA number with yours.  The dispatchPeriod variable tells the tracker how often to report back to Google.  Google suggests using 10 seconds in their example so we&#8217;ll stick to that.</p>
<h4>Tracking Pageviews and Custom Events</h4>
<p>Google gives you 2 different ways to track how your users use the application.  The first way is via pageviews.  Pageviews work just like they do in the browser as if the user navigated to a new page in your website.  Some examples of when to use pageview are when you have a tab interface or a flipside view controller.  I would not suggest using a pageview every time the user performs an action such as click a button.</p>
<p>The second way is via custom events.  These are really cool.  With custom events, you can easily see HOW your users are using your application.  Examples of events are button clicks, typing in a textbox, submitting high scores, etc&#8230;</p>
<p>We will see an example of implementing each of these methods and take a look at how they appear inside of the Google Analytics website.</p>
<p><strong>Pageview method</strong></p>
<p>Here is an example of a pageview when the user first launches the app.  Put this code inside of your applicationDidFinishLaunching method.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error;
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>GANTracker sharedTracker<span style="color: #002200;">&#93;</span> trackPageview<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;/app_launched&quot;</span>
                                        withError<span style="color: #002200;">:&amp;</span>amp;error<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
     <span style="color: #11740a; font-style: italic;">// Handle error here</span>
   <span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Note that the &#8220;app_launched&#8221; is essentially our page name similar to index.html or aboutus.php.  You can add this code anywhere in you app that you want to add a page view.  Make sure you include the GANTrack.h file and change the pagename for each new location.</p>
<p><strong>Event method</strong><br />
Here is an example of an event that gets fired when the user presses a Save button.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>IBAction<span style="color: #002200;">&#41;</span> saveTheWorld<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span> sender
<span style="color: #002200;">&#123;</span>
	<span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error;
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>GANTracker sharedTracker<span style="color: #002200;">&#93;</span> trackEvent<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;button_click&quot;</span>
				             action<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;save_the_world&quot;</span>
					      label<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;my_label&quot;</span>
					      value<span style="color: #002200;">:-</span><span style="color: #2400d9;">1</span>
					  withError<span style="color: #002200;">:&amp;</span>amp;error<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
		<span style="color: #11740a; font-style: italic;">// Handle error here</span>
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>What&#8217;s really cool about event tracking is you have 3 levels of customization.  You have the category, the action, and the label.  How you organize it is up to you, but make sure the grouping makes sense.  In the example above, I will use the category &#8220;button_click&#8221; every time a user clicks any button.  The action will determine which button was clicked (in this case, it&#8217;s &#8220;save_the_world&#8221;).  Finally, the label is just another level.  I&#8217;d suggest using the UDID of the users device.</p>
<p>Now that we have implemented our code, let&#8217;s take a look inside of our Google Analytics account and see what the stats look like.</p>
<p><a href="/wp-content/uploads/2010/04/Screen-shot-2010-04-22-at-8.48.41-AM1.png"><img class="alignnone size-full wp-image-1977" title="Screen shot 2010-04-22 at 8.48.41 AM" src="/wp-content/uploads/2010/04/Screen-shot-2010-04-22-at-8.48.41-AM1.png" alt="" width="639" height="299" /></a></p>
<p>This is just some of our sample data from another app.  Notice the interface is exactly the same as it is when you are tracking website statistics.  It shows you unique visits as well as pageviews.  You get all of the advanced reporting too including time spent on each &#8220;page&#8221;.</p>
<p>Now we take a look at events.  To find the actions click Content -&gt; Event Tracking inside of your Google Analytics Page.</p>
<p><a href="/wp-content/uploads/2010/04/Screen-shot-2010-04-22-at-8.53.30-AM1.png"><img class="alignnone size-full wp-image-1978" title="Screen shot 2010-04-22 at 8.53.30 AM" src="/wp-content/uploads/2010/04/Screen-shot-2010-04-22-at-8.53.30-AM1.png" alt="" width="608" height="339" /></a></p>
<p>In the above screenshot, we see tracking for an event called &#8220;clap&#8221;.  It shows us the number of times the users &#8220;clapped&#8221; within a given day.</p>
<h4>Conclusion</h4>
<p>One last thing I want to mention before concluding this tutorial. <strong>Google Analytics stats are 1 day behind</strong>.  What this means is, you won&#8217;t see your stats appear immediately.  So, before you comment here because you don&#8217;t see the stats appearing, please please please wait one day and check your stats again.  That is all <img src="/wp-includes/images/smilies/icon_smile.gif" alt=":)" class="wp-smiley" /></p>
<p>Be one of the cool kids, <a href="http://twitter.com/brandontreb">follow me on Twitter</a>.</p>
<p>Happy iCoding</p>
]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2010/04/22/how-to-integrate-google-analytics-tracking-into-your-apps-in-7-minutes/feed/</wfw:commentRss>
		<slash:comments>38</slash:comments>
		</item>
		<item>
		<title>iPhone Programming Tutorial &#8211; Creating a ToDo List Using SQLite Part 4</title>
		<link>http://icodeblog.com/2008/09/22/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-4/</link>
		<comments>http://icodeblog.com/2008/09/22/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-4/#comments</comments>
		<pubDate>Mon, 22 Sep 2008 23:47:39 +0000</pubDate>
		<dc:creator><![CDATA[brandontreb]]></dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[iphone programming]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[SQLite]]></category>
		<category><![CDATA[sqlite3]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=392</guid>
		<description><![CDATA[This is the final installment of our 4 part series of creating a Todo list for the iPhone.  In this tutorial, I will detail how to add and delete new todo objects from the SQLite database.  Make sure that you have completed the following tutorials before you begin this one:

<a title="Permanent Link to iPhone Programming Tutorial - Creating a ToDo List Using SQLite Part 1" rel="bookmark" href="/2008/08/19/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-1/">iPhone Programming Tutorial &#8211; Creating a ToDo List Using SQLite Part 1</a>
<a  ...]]></description>
				<content:encoded><![CDATA[<p style="text-align: left;">This is the final installment of our 4 part series of creating a Todo list for the iPhone.  In this tutorial, I will detail how to add and delete new todo objects from the SQLite database.  Make sure that you have completed the following tutorials before you begin this one:</p>
<ul style="text-align: left;">
<li><a title="Permanent Link to iPhone Programming Tutorial - Creating a ToDo List Using SQLite Part 1" rel="bookmark" href="/2008/08/19/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-1/">iPhone Programming Tutorial &#8211; Creating a ToDo List Using SQLite Part 1</a></li>
<li><a title="Permanent Link to iPhone Programming Tutorial - Creating a ToDo List Using SQLite Part 1" rel="bookmark" href="/2008/09/02/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-2/">iPhone Programming Tutorial &#8211; Creating a ToDo List Using SQLite Part 2</a></li>
<li><a href="/2008/09/10/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-3/">iPhone Programming Tutorial &#8211; Creating a ToDo List Using SQLite Part 3</a></li>
</ul>
<p style="text-align: left;">When you have completed this tutorial, you should have a main screen that looks something like this:</p>
<p style="text-align: left;"><a href="/wp-content/uploads/2008/09/mainscreen1.png"><img class="size-full wp-image-394 aligncenter" title="screenshot" src="/wp-content/uploads/2008/09/mainscreen1.png" alt="" width="386" height="742" /></a></p>
<p style="text-align: left;">Let&#8217;s get started&#8230;</p>
<p style="text-align: left;">The first thing we need to do is add the UIBarButtonItem items to the NavigationBar so that we get the &#8220;Edit&#8221; and &#8220;Add&#8221; button.  Open up <strong>RootViewController.m</strong> and add the following code to the <strong>viewDidLoad</strong> method.</p>
<p style="text-align: left;"><a href="/wp-content/uploads/2008/09/viewdidload1.png"><img class="size-full wp-image-396 aligncenter" title="viewdidload" src="/wp-content/uploads/2008/09/viewdidload1.png" alt="" width="500" height="107" /></a></p>
<p style="text-align: left;">The first thing we see is the line that sets the leftBarButtonItem to self.editButtonItem.  This automatically adds the &#8220;Edit&#8221; button to the NavigationController.  Also, it sets up the functionality that allows the &#8220;delete&#8221; buttons to be displayed when the button is pressed.  You can see this functionality if you do a &#8220;Build and Go&#8221; at this step.  Next, I have manually created a UIBarButtonItem and added it to the navigationbar.  This can be done in Interface Builder, but I wanted to show you how to do it manually and assign an action to it (I&#8217;m sure you will require this functionality in a future program).  Here is a break down of the parameters:</p>
<ul style="text-align: left;">
<li>initWithTitle &#8211; The text to be displayed on the button</li>
<li>style &#8211; How the button will look</li>
<li>target &#8211; The class object that handles the messages sent from this button</li>
<li>action &#8211; The method to be called when the button is passed.  We can use @selector and give it the name of the function to call.</li>
</ul>
<p style="text-align: left;">Finally, we assign this button to the rightBarButtonItem.  If you do a Build and Go, it should error since we haven&#8217;t created the addTodo method. We will do that in a bit.  Now, let&#8217;s create a method inside of our Todo object that will add new Todos to the database.</p>
<p style="text-align: left;">Open up <strong>Todo.h</strong> and add the following code:</p>
<p style="text-align: left;"><a href="/wp-content/uploads/2008/09/todo1.png"><img class="alignnone size-full wp-image-398" title="todo" src="/wp-content/uploads/2008/09/todo1.png" alt="" width="363" height="33" /></a></p>
<p style="text-align: left;">So in addition to the <strong>insertNewTodoIntoDatabase</strong> method, we also see the deleteFromDatabase method signature.  I have just added this so I don&#8217;t have to come back to it later.  We will be implementing this when I show you how to delete todos from the database.  One thing to note about the <strong>insertNewTodoIntoDatabase </strong>method is it has a &#8220;+&#8221; rather than a &#8220;-&#8221; sign.  This means that it is a static method.  Static methods are associated with the class not the instance meaning we can call this method without instanciating this class.  So we can do stuff like Todo.insertNewTodoIntoDatabase.  Now we will implement this method.</p>
<p style="text-align: left;">Before we can do this, we must declare a few more static sqlite3_statement&#8217;s.  Add the following statements to the top of <strong>Todo.m</strong></p>
<p style="text-align: left;"><a href="/wp-content/uploads/2008/09/todomstatic1.png"><img class="size-full wp-image-400 aligncenter" title="todomstatic" src="/wp-content/uploads/2008/09/todomstatic1.png" alt="" width="270" height="30" /></a></p>
<p style="text-align: left;">Nothing new here&#8230;Now implement the following method:</p>
<p style="text-align: left;"><a href="/wp-content/uploads/2008/09/todom31.png"><img class="size-full wp-image-399 aligncenter" title="todom3" src="/wp-content/uploads/2008/09/todom31.png" alt="" width="499" height="197" /></a></p>
<p style="text-align: left;">This is similar to our update method.  Notice that we are inserting default values into the database.  This is so we don&#8217;t run into any problems with null or nil values.  The most important part of this method is the fact that it returns the primary key of the newly created todo object.  This will be used later so we can immediately transition to the todo when the &#8220;Add&#8221; button is pressed.  The last thing we need to do to the todo object is update the dehydrate method so that the todoText gets saved if it gets changed.  Update the dehydrate method to look like this:</p>
<p style="text-align: left;"><a href="/wp-content/uploads/2008/09/dehydrate1.png"><img class="size-full wp-image-401 aligncenter" title="dehydrate" src="/wp-content/uploads/2008/09/dehydrate1.png" alt="" width="500" height="257" /></a></p>
<p style="text-align: left;">There are only a few minor changes here.  First we see the &#8220;text = ?&#8221; part added to the sql statement.  This is simply so we can update the text of the todo.  The other change is we bound the self.text property to the 1st question mark in the sql statement.  One thing to notice is we call [self.text UTF8String].  This is because sqlite3_bind_text takes a (char *).  This will convert an NSString to an acceptable format.</p>
<p style="text-align: left;">Now we need to add a method inside of our RootViewController to add a todo.  This is the method that will be called when the user presses the &#8220;Add&#8221; button.  Inside of RootViewController.m add the following code:</p>
<p><a href="/wp-content/uploads/2008/09/1-rootviewcontroller1.png"><img class="size-full wp-image-422 aligncenter" title="1-rootviewcontroller" src="/wp-content/uploads/2008/09/1-rootviewcontroller1.png" alt="" width="500" height="179" /></a></p>
<p style="text-align: left;">First, we get a reference to the appDelegate object.  This is because we need to call its addTodo method.  Next, we instantiate the TodoViewController if it has not already been instantiated.  We need this around because we will push it on to the view stack and transition to it after we create our new todo object.  After this is done, we call the addTodo method of the appDelegate.  It will return the newly created todo object and the view will be transitioned to its detail screen in order to update its details.  Now we need to implement the method addTodo inside of our appDelegate.  Open up todoAppDelegate.h and add the following code to create the method signature.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/2-appdelegateh1.png"><img class="size-full wp-image-423 aligncenter" title="2-appdelegateh" src="/wp-content/uploads/2008/09/2-appdelegateh1.png" alt="" width="107" height="18" /></a></p>
<p style="text-align: left;">
<p style="text-align: left;">Now, let&#8217;s implement this method.  Open up todoAppDelegate.m and add the following code:</p>
<p style="text-align: left;">
<p style="text-align: left;"><a href="/wp-content/uploads/2008/09/3-appdelegatem1.png"><img class="size-full wp-image-424 aligncenter" title="3-appdelegatem" src="/wp-content/uploads/2008/09/3-appdelegatem1.png" alt="" width="500" height="101" /></a></p>
<p style="text-align: left;">
<p>First, we are calling the insertNewTodoIntoDatabase method of the Todo object.  Notice that we are simply calling the method without first building an instance of a todo object.  As I said in tutorial 3, this is because that method is static and gets called without building an instance of the class.  Next, we insatiate the todo object that was just created by calling its initWithPrimaryKey method.  This will give us reference to the new todo object.  Finally, we append this todo to the end of our todos array.  Since our UITableView is updated with this array, it will automatically include the new todo object.  The last line just returns this todo object.</p>
<p>Remember is the last tutorial we made it so the users could update the status and the priority of a todo?  Well, now we also need to give them the ability to update the text of the todo.  So open up TodoViewController.h and add the following code:</p>
<p style="text-align: center;">
<p><a href="/wp-content/uploads/2008/09/5-todoviewcontrollerh1.png"><img class="alignnone size-full wp-image-425" title="5-todoviewcontrollerh" src="/wp-content/uploads/2008/09/5-todoviewcontrollerh1.png" alt="" width="430" height="271" /></a><a href="/wp-content/uploads/2008/09/5-todoviewcontrollerh1.png"><br />
</a></p>
<p style="text-align: left;">
<p>Ok, so I&#8217;m guessing you are wondering why the UITextView for the todoText object has been changed to a UITextField.  Well, I will tell you.  UITextView doesn&#8217;t have the methods that we need to save the text with our current design.  We will also be changing this on our Interface inside of Interface Builder.  So for now, just believe me and anywhere it says UITextView, change it to UITextField.  The only additional code we added here is the method signature for the updateText method.  It&#8217;s an IBAction that will get called when the user presses the &#8220;Done&#8221; button on the keyboard after setting the text for the todo.  Next, we need to implement this method.  Open up TodoViewController.m and add the following code:</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/5-todoviewcontrollerm1.png"><img class="size-full wp-image-426 aligncenter" title="5-todoviewcontrollerm" src="/wp-content/uploads/2008/09/5-todoviewcontrollerm1.png" alt="" width="245" height="53" /></a></p>
<p style="text-align: left;">All this does is update the text of the todo to the text that the user entered inside of the UITextField.  The last thing we need to do in order to add a todo is to replace the UITextView with a UITextField and connect it to our updateText method.  Double click on your TodoViewController.xib file to open it in Interface Builder.</p>
<p>Now click on the UITextView on your interface and press the delete key on your keyboard to delete it.  Now, drag a UITextField from the library and drop it onto your interface.  Resize it to fit.  When you have completed that, your interface should look something like this:</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/6-interfacebuilder1.png"><img class="size-full wp-image-427 aligncenter" title="6-interfacebuilder" src="/wp-content/uploads/2008/09/6-interfacebuilder1.png" alt="" width="320" height="502" /></a></p>
<p style="text-align: left;">Now we need to connect this component.  Make sure it is selected and click Tools -&gt; Connections Inspector to open up the connections inspector.  Drag from the circle next to the method &#8220;Did End On Exit&#8221; to the &#8220;File&#8217;s Owner&#8221; object.  The words udpateText should pop up.  Click on them to make the connection.  Next, click in the circle next to &#8220;New Referencing Outlet&#8221; and drag it to the &#8220;File&#8217;s Owner&#8221; object.  Select todoText  when it pops up.  The Connections Inspector should look like this:</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/12-ib1.png"><img class="size-full wp-image-434 aligncenter" title="12-ib" src="/wp-content/uploads/2008/09/12-ib1.png" alt="" width="287" height="708" /></a></p>
<p>Now we are done with Interface Builder.  Go ahead and close it.  We are now able to add todos.  The last thing we need to do is give the ability to delete todos from the list as well as our database.  This is all done in code, and we won&#8217;t need interface builder for this.</p>
<p>Let&#8217;s start by adding the methods to the appDelegate to handle the deletion of todos.  Open up todoAppDelegate.h and add the following code:</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/7-appdelegateh1.png"><img class="alignnone size-full wp-image-428" title="7-appdelegateh" src="/wp-content/uploads/2008/09/7-appdelegateh1.png" alt="" width="194" height="16" /></a></p>
<p style="text-align: left;">All we see here is a signature for the removeTodo method.  Also, be sure to add a #import &#8220;Todo.h&#8221; statement to the top of this file so that we can interface with the todo objects. Now let&#8217;s implement the removeTodo method.  Open up todoAppDelegate.m and add the following code:</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/8-appdelegatem1.png"><img class="size-full wp-image-429 aligncenter" title="8-appdelegatem" src="/wp-content/uploads/2008/09/8-appdelegatem1.png" alt="" width="308" height="119" /></a></p>
<p style="text-align: left;">The first line looks up the todo in the todos NSArray.  It returns the index in the array of the todo to be deleted.  Then, we call the deleteFromDatabase method on the todo object and then remove it from the todos array.  Since the UITableView is updated via this array, it will automatically remove the todo without any additional code on our part.</p>
<p>Now, let&#8217;s create the removeTodo method for the todo object. We have already written the method signature in Todo.h in a previous step, so open up Todo.m and add the following code:</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/10-todom1.png"><img class="size-full wp-image-431 aligncenter" title="10-todom" src="/wp-content/uploads/2008/09/10-todom1.png" alt="" width="500" height="182" /></a></p>
<p style="text-align: left;">Remember the delete_statement variable is a static sqlite3_stmt that we declared in a previous step.  First, we check to see if it is nil.  If it is we compile the statement using the sqlite3_prepare statement.  Next, we bind the primary key of the current todo to the &#8220;?&#8221; in the sqlite3 statement.  Next, we just step the statement to execute it and reset it.  The last thing we need to do to delete todos from the database is to specify what happens when the user presses the &#8220;delete&#8221; button.  Open up RootViewController.m and add the following code:</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/11-rootviewcontroller11.png"><img class="size-full wp-image-432 aligncenter" title="11-rootviewcontroller1" src="/wp-content/uploads/2008/09/11-rootviewcontroller11.png" alt="" width="499" height="143" /></a></p>
<p style="text-align: left;">
<p style="text-align: left;">The first step (like the first step of many functions) is to get a reference to the appDelegate.  Next, we check to see if we are currently editing.  If so, call the removeTodo method on appDelegate.  The next line, removes the row from the UITableView at the given indexPath.</p>
<p>Now click Build and Go!  You should now be able to add and delete todo items from the database.  This concludes our four part series of creating a todo list for the iPhone.  As always, if you have any questions feel free to leave them in the comments section.  If you get lost at any time you can download the sample code <a href="/wp-content/uploads/2008/09/todo-part-41.zip">here</a>.</p>
<p>Happy iCoding!</p>
<p style="text-align: left;">
]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2008/09/22/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-4/feed/</wfw:commentRss>
		<slash:comments>115</slash:comments>
		</item>
		<item>
		<title>iPhone Programming Tutorial &#8211; Creating a ToDo List Using SQLite Part 3</title>
		<link>http://icodeblog.com/2008/09/10/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-3/</link>
		<comments>http://icodeblog.com/2008/09/10/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-3/#comments</comments>
		<pubDate>Thu, 11 Sep 2008 01:39:29 +0000</pubDate>
		<dc:creator><![CDATA[brandontreb]]></dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Interface Builder]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[iphone programming]]></category>
		<category><![CDATA[SQLite]]></category>
		<category><![CDATA[todo]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[uitableview]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=339</guid>
		<description><![CDATA[This is part 3 in our multipart series of creating a todo list for the iPhone.  For this, you must have completed the following tutorials.

<a title="Permanent Link to iPhone Programming Tutorial - Creating a ToDo List Using SQLite Part 1" rel="bookmark" href="/2008/08/19/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-1/">iPhone Programming Tutorial &#8211; Creating a ToDo List Using SQLite Part 1</a>
<a title="Permanent Link to iPhone Programming Tutorial - Creating a ToDo List Using SQLite Part 1" rel="bookmark" href="/2008/09/02/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-2/">iPhone Programming Tutorial &#8211; Creating a ToDo List Using SQLite  ...]]></description>
				<content:encoded><![CDATA[<p style="text-align: left;">This is part 3 in our multipart series of creating a todo list for the iPhone.  For this, you must have completed the following tutorials.</p>
<ul>
<li><a title="Permanent Link to iPhone Programming Tutorial - Creating a ToDo List Using SQLite Part 1" rel="bookmark" href="/2008/08/19/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-1/">iPhone Programming Tutorial &#8211; Creating a ToDo List Using SQLite Part 1</a></li>
<li><a title="Permanent Link to iPhone Programming Tutorial - Creating a ToDo List Using SQLite Part 1" rel="bookmark" href="/2008/09/02/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-2/">iPhone Programming Tutorial &#8211; Creating a ToDo List Using SQLite Part 2</a></li>
</ul>
<p>The focus of this tutorial will mainly be on viewing the todo items when selected.  I will also show you how to update the todo status.  This will require us to use interface builder.  When you are completed, you will be able to edit todos through an interface similar to this:</p>
<p style="text-align: center; "><a href="/wp-content/uploads/2008/09/screenshot11.png"><img class="size-full wp-image-390 aligncenter" title="screenshot1" src="/wp-content/uploads/2008/09/screenshot11.png" alt="" width="386" height="742" /></a></p>
<h2>Bringing Your Code Up To Speed</h2>
<p>For this tutorial, we will need to get the last variable from the todo database.  This is of course being the status variable.  If you recall, it&#8217;s a boolean value (1 for complete, 0 for in progress).  We need to get it from the database and associate it with the todo object.  First let&#8217;s create a property to hold this value.  Open todo.h and add the following code:</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/todoh11.png"><img class="alignnone size-full wp-image-370" title="todoh1" src="/wp-content/uploads/2008/09/todoh11.png" alt="" width="393" height="329" /></a></p>
<p style="text-align: left;">So a few changes here&#8230;First there is the added NSInteger status.  This will be the property we associate with the status (complete or not) of the todo.  We also create a property from it.  Next, there is a BOOL property called &#8220;dirty&#8221;.  We will use this object to signify when a todo has been altered.  You will see how this comes into play when we implement the dehydrate method. Also, I have added 3 method signatures.  updateStatus will be the method called when we want to update our status variable.  Similarly, the updatePriority method will be called to update the priority.  Finally, we have added a dehydrate method.  This method should be familiar (or confusing) if you have messed with Apple&#8217;s books example.  Basically, it will be used to save the state of the todo to the database.  We will be calling this method on each todo item when the program exits.  I will show you how to do this in a little bit.</p>
<p style="text-align: left;">Be sure to add the status variable to the synthesize line.  Also, as we did before, we need to create a static sqlite3_stmt to hold the compiled dehydration statement.  Add the following code to Todo.m:</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/synth11.png"><img class="alignnone size-full wp-image-382" title="synth1" src="/wp-content/uploads/2008/09/synth11.png" alt="" width="280" height="74" /></a></p>
<p style="text-align: left;">Now let&#8217;s implement the methods.  Add the following code:</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/todom21.png"><img class="size-full wp-image-371 aligncenter" title="todom2" src="/wp-content/uploads/2008/09/todom21.png" alt="" width="500" height="379" /></a></p>
<p style="text-align: left;">The first two methods (udpateStatus and updatePriority) are pretty strait forward.  They update the status and the priority of the todo and then set the &#8220;dirty&#8221; property to 1.  This signifies that the todo has been altered and will need to be saved to the database.</p>
<p style="text-align: left;">Finally, there is the dehydrate method&#8230; We will call this method on each todo upon termination of the program.  If the todo is &#8220;dirty&#8221; meaning the dirty property was set to YES, we will need to save the new data to the database.  The database code should look pretty similar to code in previous tutorials.  First, we check to see if the dehydrate_statement is equal to nil.  If you recall, this will only happen the first time this method gets called.  Next we create the update statement and then bind our variables to each of the &#8220;?&#8221;&#8216;s.  Notice the ordering.  The numbers represent the question marks from left to right (1 being the first, 2 being the second, 3 being the third).  It took me quite some time to figure this out.  Finally, we execute the sqlite statement by calling sqlite3_step and then reset the statement.</p>
<p style="text-align: left;">The last thing we need to do to Todo.m is change the SELECT statement in the initWithPrimaryKey method to grab the &#8216;complete&#8217; field.  Update the code to look like the screenshot below:</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/00-todom1.png"><img class="size-full wp-image-357 aligncenter" title="00-todom" src="/wp-content/uploads/2008/09/00-todom1.png" alt="" width="500" height="322" /></a></p>
<p style="text-align: left;">There are not really many changes.  The first change is the added status to the synthesize line.  Next, the sql statement was updated to read</p>
<p style="text-align: left;">SELECT text,priority,complete FROM todo WHERE pk=?</p>
<p style="text-align: left;">This allows us to get the &#8220;complete&#8221; field from the database.  Finally, there is the line &#8220;self.status = sqlite3_column_in(init_statement,2);&#8221;.  This is assigning the status property to the data at index 2 in the sql data array.  We can now use this field.</p>
<p style="text-align: left;">One thing we need to do for the navigation to function properly is add a title to our main view.  Open up rootViewController.m and add the following code to the viewDidLoad method:</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/title1.png"><img class="alignnone size-full wp-image-381" title="title" src="/wp-content/uploads/2008/09/title1.png" alt="" width="175" height="16" /></a></p>
<h2>Create the Todo Detail View</h2>
<p>Now we are going to create the view that will display when the user selects the todo in the UITableView.  Go ahead and open up Interface Builder by selecting one of you existing nib (.xib) files.  Once it&#8217;s open add a new View by clicking <strong>File -&gt; New</strong> and select <strong>View.</strong> Drag the following controls.</p>
<ul>
<li>UITextView</li>
<li>UISegmentedControl &#8211; For this you will need to set the number of segments to 3.  You will also see a dropdown menu below this option.  Select each segment and fill in one of the priorities for the title.  Here is a screenshot. You should give a title to each (Low , Medium, High).
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/segmented-control1.png"><img class="alignnone size-full wp-image-340" title="segmented-control" src="/wp-content/uploads/2008/09/segmented-control1.png" alt="" width="287" height="708" /></a></p>
</li>
<li>UILabel &#8211; This will be used to display the status</li>
<li>UIButton &#8211; Users will click this button to update the status (Mark as complete)</li>
</ul>
<p>When you are done, your interface should look something like this (but probably better):</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/ibscreenshot1.png"><img class="alignnone size-full wp-image-369" title="ibscreenshot" src="/wp-content/uploads/2008/09/ibscreenshot1.png" alt="" width="320" height="502" /></a></p>
<p style="text-align: left;">I know that my interface doesn&#8217;t look the coolest.  I&#8217;m a programmer not a graphic designer&#8230; Ok save this view by pressing Command-S.  Make sure you are in your current projects directory.  Name it <strong>TodoViewController</strong> and press Save<strong>. </strong></p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/2-save1.png"><img class="size-full wp-image-343 aligncenter" title="2-save" src="/wp-content/uploads/2008/09/2-save1.png" alt="" width="500" height="392" /></a></p>
<p style="text-align: left;">It will then ask you if you want to add it to your project. Check the box next to the word todo and click Add.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/3-save1.png"><img class="alignnone size-full wp-image-344" title="3-save" src="/wp-content/uploads/2008/09/3-save1.png" alt="" width="431" height="290" /></a></p>
<p style="text-align: left;">Now close Interface Builder.  Next, we are going to add the viewController class and set up variables to interface with this view.</p>
<h2 style="text-align: left;">Create TodoViewController Class Files</h2>
<p>Click <strong>File -&gt; New File&#8230;</strong> Select <strong>UIViewController Subclass</strong> and click Next.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/08/14addviewcontrollerclass1.png"><img class="size-full wp-image-212 aligncenter" title="14addviewcontrollerclass" src="/wp-content/uploads/2008/08/14addviewcontrollerclass1.png" alt="" width="500" height="368" /></a></p>
<p style="text-align: left;">Name the file <strong>TodoViewController</strong> and make sure that the box that says &#8220;Also create TodoViewController.h&#8221; is checked and click Finish.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/4-viewcontroller1.png"><img class="size-full wp-image-345 aligncenter" title="4-viewcontroller" src="/wp-content/uploads/2008/09/4-viewcontroller1.png" alt="" width="500" height="368" /></a></p>
<p style="text-align: left;">Open up TodoViewController.h and add the following code.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/04-todoviewcontroller1.png"><img class="alignnone size-full wp-image-359" title="04-todoviewcontroller" src="/wp-content/uploads/2008/09/04-todoviewcontroller1.png" alt="" width="430" height="300" /></a></p>
<p style="text-align: left;">Basically, we are setting up Interface Builder Outlets for each of the UI components to be connected to.  Notice, the UIButton has an IBOutlet.  This is because we will need to update the text on the button depending on whether or not the todo is completed.  Also, I have an IBAction called updateStatus.  We will be connecting this to the button we created.  It will toggle the status (pending/complete) of a todo item.  Finally, we see the updatePriority method.  This method will be called when the user selects one of the priority segments in the UISegmentedControl. Next, open up TodoViewController.m and add the following synthesize code:</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/synthtodoviewcontroller11.png"><img class="alignnone size-full wp-image-364" title="synthtodoviewcontroller1" src="/wp-content/uploads/2008/09/synthtodoviewcontroller11.png" alt="" width="374" height="22" /></a></p>
<p style="text-align: left;">This will allow us to get and set these variables.</p>
<p style="text-align: left;">Before we connect this code to the Interface, we need to implement the methods that will be called when the user presses the button to mark a todo as complete as well as when the user presses a segment in the UISegmentedControl.  Inside of TodoViewController add the following methods.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/todoviewcontrollerm1.png"><img class="size-full wp-image-368 aligncenter" title="todoviewcontrollerm" src="/wp-content/uploads/2008/09/todoviewcontrollerm1.png" alt="" width="500" height="229" /></a></p>
<p style="text-align: left;">Let&#8217;s go through this.  First we see the updateStatus method.  This gets called when a user presses the button to alter the status.  We basically check the current status of the todo (whether or not it&#8217;s completed) and depending on that, change the text to be displayed on the UIButton.  So, if the todo is not complete (in progress) and this button is pressed, the text will be changed from &#8220;Mark As Complete&#8221; to &#8220;Mark As In Progress&#8221;.  Finally, we call the updateStatus of the todo and pass the new value (1 or 0) to it.</p>
<p style="text-align: left;">Next we see the updatePriority method.  It simply reads the value of the UISegmentedControl by calling the selectedSegmentIndex method on it.  The next part looks a little messy.   There are 2 reasons that reason we can&#8217;t just pass the value of the UISegmentedControl directly to the method.  The first is, the UISegmentedControl is ordered in acending order (1, 2, 3&#8230;), but our priorities are in descending order (3 = low, 2 = medium, 1 = high).  This is where the &#8220;2 &#8211; priority&#8221; comes from.  Next, UISegmented controls are &#8220;0 indexed&#8221; meaning the indices start at 0 and increment from there.  So we need to add a &#8220;+1&#8243; to the index as our todo priorities start at 1.</p>
<p style="text-align: left;">Now we need to connect the UI Components in Interface Builder to this code.  Double click on TodoViewController.xib to open it in Interface Builder.</p>
<h2 style="text-align: left;">Connecting UI Components To Code</h2>
<p>We first need to associate this view with the class we just created.  In the Interface Builder, click on the File&#8217;s Owner object.  Next click <strong>Tools -&gt; Identity Inspector</strong>.  You should see a drop-down next to class.  Select TodoViewController from this list and you will see the variables we just created appear in the boxes below.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/07-files-owner1.png"><img class="size-full wp-image-349 aligncenter" title="07-files-owner" src="/wp-content/uploads/2008/09/07-files-owner1.png" alt="" width="305" height="287" /></a></p>
<p style="text-align: left;">This is what the Identity window should look like after you have selected TodoViewController.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/todoviewcontrollerfilesowner1.png"><img class="alignnone size-full wp-image-380" title="todoviewcontrollerfilesowner" src="/wp-content/uploads/2008/09/todoviewcontrollerfilesowner1.png" alt="" width="287" height="708" /></a></p>
<p style="text-align: left;">Now that the class is associated, we can begin connecting the components.  We will start by connecting the view.  Click on the top of your view window to select the view itself (make sure you haven&#8217;t selected any of the UI components).  Click <strong>Tools -&gt; Connections Inspector</strong>.  Next to where is says &#8220;New Referencing Outlet&#8221; click in the circle and drag it to the &#8220;File&#8217;s Owner&#8221; object and release it.  The word &#8220;view&#8221; should pop up.  Click on the word view.  It should now look like this.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/08-view-connect1.png"><img class="size-full wp-image-350 aligncenter" title="08-view-connect" src="/wp-content/uploads/2008/09/08-view-connect1.png" alt="" width="287" height="708" /></a></p>
<p style="text-align: left;">Now repeat these steps for each of the components (UITextView, UISegmentedControl, UILabel, UIButton) connecting each to the &#8220;File&#8217;s Owner Object&#8221;.   Instead of the word &#8220;view&#8221; popping up, you should see the variable name for the corresponding variable that you want to connect the component to.   So for the UITextView, you should see the word &#8220;todoText&#8221; appear when you drag it to the File&#8217;s Owner object.</p>
<p style="text-align: left;">We need to connect the UIButton to the updateStatus method we created.  To do this click inside the &#8220;Touch up inside&#8221; circle and drag it to the &#8220;File&#8217;s Owner&#8221; object.  You should see the text &#8220;updateStatus&#8221; appear.  Click on it.  If all goes well it should look like this.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/uibutton11.png"><img class="alignnone size-full wp-image-362" title="uibutton1" src="/wp-content/uploads/2008/09/uibutton11.png" alt="" width="287" height="708" /></a></p>
<p style="text-align: left;">The last thing we need to do inside of Interface Builder is connect the UISegmentedControl.  Click on it in your view and then click <strong>Tools -&gt; Connections Inspector&#8230;</strong> Click on the circle next to the &#8220;Value Changed&#8221; method and drag it to the &#8220;File&#8217;s Owner&#8221; object.  You will see the method updatePriority popup.  Go ahead and click on it.  Your window for the UISegmentedControl should now look like this:</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/uisegementedcontrol11.png"><img class="alignnone size-full wp-image-366" title="uisegementedcontrol1" src="/wp-content/uploads/2008/09/uisegementedcontrol11.png" alt="" width="287" height="708" /></a></p>
<p style="text-align: left;">Now, let&#8217;s display this view when a row is selected.  Close Interface Builder and open up RootViewController.h and add the following code:</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/11-rootviewcontroller2.png"><img class="size-full wp-image-354 aligncenter" title="11-rootviewcontroller" src="/wp-content/uploads/2008/09/11-rootviewcontroller2.png" alt="" width="352" height="149" /></a></p>
<p style="text-align: left;">We need a variable to associate with the TodoViewController that we will be transitioning to.  Next, open up RootViewController.m and add the following code to synthesize this property.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/12-synth1.png"><img class="size-full wp-image-355 aligncenter" title="12-synth" src="/wp-content/uploads/2008/09/12-synth1.png" alt="" width="133" height="21" /></a></p>
<h2 style="text-align: left;">Keeping the UITableView Up To Date</h2>
<p style="text-align: left;">Whenever a todo item is altered (status or priority) the UITableView needs to be updated with the new changes.  Add the following code to the viewWillAppear.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/rootviewcontrollermwillapprea1.png"><img class="size-full wp-image-372 aligncenter" title="rootviewcontrollermwillapprea" src="/wp-content/uploads/2008/09/rootviewcontrollermwillapprea1.png" alt="" width="246" height="65" /></a></p>
<p style="text-align: left;">The line [self.tableView reloadData] reloads the table data every time the view appears (or reappears).  This will ensure that our table is always up to date.</p>
<p style="text-align: left;">Now add the following code to the didSelectRowAtIndex method:</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/didselectrowatindex1.png"><img class="size-full wp-image-373 aligncenter" title="didselectrowatindex" src="/wp-content/uploads/2008/09/didselectrowatindex1.png" alt="" width="500" height="341" /></a></p>
<p style="text-align: left;">This is quite a bulky method with a lot of familiar code.  First, we get a handle to the appDelegate and the todo object that was selected.  Next, we push the todoView (the view you created in interface builder) on to the viewController stack to transition to it.  After that, we are setting some of the properties of the view.  The title is set to the text of the todo (it will get truncated if it is too long) and the UITextView is also set to the todo text.  Next, we are translating our priority to an index for the UISegmentedView.  I explained why this was necessary above.  Then the index of the UISegmentedControl is set by using the setSelectedSegmentIndex method.  Finally, we set the text of the button and label based on the status of the todo.</p>
<p style="text-align: left;">The very last thing we need to do is tell the application to save itself when it closes.  Open up todoAppDelegate.m and add the following code to the applicationWillTerminate method:</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/applicationwillterminate1.png"><img class="size-full wp-image-374 aligncenter" title="applicationwillterminate" src="/wp-content/uploads/2008/09/applicationwillterminate1.png" alt="" width="388" height="64" /></a></p>
<p style="text-align: left;">If you ask me, this is some freakin sweet functionality.  The method &#8220;makeObjectsPerformSelector&#8221; is a built in method on an NSArray.  It basically loops over every object in the array, calling the method you pass in to it on each one.  It&#8217;s like doing a for loop and calling the todo[x].dehydrate method for each todo.  Only this is much cleaner.  So, to reiterate, this method will call the dehydrate method on each todo.  If the todo is &#8220;dirty&#8221; meaning it was altered, it will be saved to the database, otherwise the dehydrate method will do nothing.</p>
<p style="text-align: left;">* One thing to note.  The applicationWillTerminate method will not be called if you quit the simulator while the application is running.  To make sure it gets called (and the todo data gets saved) make sure you press the home button on the simulator after you make alterations to the todos.  If you simply press Apple-q and quit the simulator while inside of the todo program, no data will be saved and you will post angry comments on my site telling me that my tutorial is wrong.</p>
<p style="text-align: left;">Click Build and Go and just sit back and enjoy the magic of rock! I mean XCode&#8230;</p>
<p style="text-align: left;">When you select a todo item, your screen should look something like this:</p>
<p style="text-align: center; "><a href="/wp-content/uploads/2008/09/screenshot11.png"><img class="size-full wp-image-390 aligncenter" title="screenshot1" src="/wp-content/uploads/2008/09/screenshot11.png" alt="" width="386" height="742" /></a></p>
<p style="text-align: left;">Well, that concludes part 3 of our series.  Join me next time, when I will show you how to add and delete todos from the SQLite database. If you have any comments or questions, feel free to leave them in the comments section.  I would love to hear them.  Please <a href="http://feeds.feedburner.com/icodeblog">subscribe to the RSS feed</a> if you want to be automatically notified of new tutorials.  If you get lost at any point, you can download the sample code for this tutorial <a href="/wp-content/uploads/2008/09/todo-part-31.zip">here</a>.</p>
<p style="text-align: left;">Happy iCoding!</p>
<p style="text-align: left;">
<p style="text-align: left;">
]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2008/09/10/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-3/feed/</wfw:commentRss>
		<slash:comments>68</slash:comments>
		</item>
		<item>
		<title>iPhone Programming Tutorial &#8211; Creating a ToDo List Using SQLite Part 2</title>
		<link>http://icodeblog.com/2008/09/02/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-2/</link>
		<comments>http://icodeblog.com/2008/09/02/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-2/#comments</comments>
		<pubDate>Tue, 02 Sep 2008 17:35:46 +0000</pubDate>
		<dc:creator><![CDATA[brandontreb]]></dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[iphone programming]]></category>
		<category><![CDATA[SQLite]]></category>
		<category><![CDATA[sqlite3]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[xcode]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=293</guid>
		<description><![CDATA[
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.

<a href="/2008/08/19/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-1/">iPhone Programming Tutorial &#8211; Creating a ToDo List Using SQLite Part 1</a>

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:
<a href="/wp-content/uploads/2008/09/screenshot2.png"></a>
In this section, I will not only teach you how to  ...]]></description>
				<content:encoded><![CDATA[<p><script type="text/javascript"><!--
digg_url = 'http://digg.com/programming/iPhone_Programming_Tutorial_Creating_a_ToDo_List_Using_SQL';
// --></script><script src="http://digg.com/api/diggthis.js"></script></p>
<p>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.</p>
<ul>
<li><a href="/2008/08/19/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-1/">iPhone Programming Tutorial &#8211; Creating a ToDo List Using SQLite Part 1</a></li>
</ul>
<p>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:</p>
<p style="text-align: center; "><a href="/wp-content/uploads/2008/09/screenshot2.png"><img class="alignnone size-full wp-image-327" title="screenshot" src="/wp-content/uploads/2008/09/screenshot2.png" alt="" width="386" height="742" /></a></p>
<p>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 <strong>multiple columns</strong> with images and text.  For this tutorial, you will need to download the following images.</p>
<ul>
<li><a href="/wp-content/uploads/2008/09/red1.png"><img class="alignnone size-full wp-image-304" title="red1" src="/wp-content/uploads/2008/09/red1.png" alt="" /></a></li>
<li><a href="/wp-content/uploads/2008/09/green1.png"><img class="alignnone size-full wp-image-305" title="green1" src="/wp-content/uploads/2008/09/green1.png" alt="" /></a></li>
<li><a href="/wp-content/uploads/2008/09/yellow1.png"><img class="alignnone size-full wp-image-306" title="yellow" src="/wp-content/uploads/2008/09/yellow1.png" alt="" /></a></li>
</ul>
<p>We will be using these images to denote the priority (Green = low, Yellow = medium, Red = high).</p>
<h2>Bring Your Code Up To Speed</h2>
<p>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:</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/todoh2.png"><img class="size-full wp-image-308 aligncenter" title="todoh" src="/wp-content/uploads/2008/09/todoh2.png" alt="" width="378" height="146" /></a></p>
<p style="text-align: left;">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.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/todom12.png"><img class="size-full wp-image-310 aligncenter" title="todom1" src="/wp-content/uploads/2008/09/todom12.png" alt="" width="499" height="326" /></a></p>
<p style="text-align: left;">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.</p>
<h2>Add Images to Your Project</h2>
<p>Download the images above and save them to your project directory.  Inside of your project, right click (control-click) on the <strong>Resources</strong> folder and click <strong>Add -&gt; Existing Files&#8230;</strong> Browser for the images, select all of them and click <strong>Add</strong>. Check the box that sais &#8220;Copy items into destination group&#8217;s folder (if needed)&#8221;.  Click <strong>Add. </strong>The image files should now appear inside of your <strong>Resources </strong>folder.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/add-images1.png"><img class="size-full wp-image-300 aligncenter" title="add-images" src="/wp-content/uploads/2008/09/add-images1.png" alt="" width="400" height="374" /></a></p>
<h2>Create a UITableViewCell Subclass</h2>
<p>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.</p>
<p>Click <strong>File -&gt; New File&#8230;</strong> and select <strong>UITableViewCell</strong>. Click <strong>Next.</strong></p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/uitableviewcell1.png"><img class="size-full wp-image-295 aligncenter" title="uitableviewcell" src="/wp-content/uploads/2008/09/uitableviewcell1.png" alt="" width="500" height="368" /></a></p>
<p>Name this file <strong>TodoCell</strong> and make sure this that the box that sais &#8220;Also create TodoCell.h&#8221; is checked.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/todocell1.png"><img class="size-full wp-image-296 aligncenter" title="todocell" src="/wp-content/uploads/2008/09/todocell1.png" alt="" width="500" height="368" /></a></p>
<p style="text-align: left;">This will create a &#8220;barebones&#8221; UITableViewCell object with some basic methods already filled out.  Let&#8217;s add some properties to this class.  Open up <strong>TodoCell.h</strong> and add the following code.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/todocellh1.png"><img class="alignnone size-full wp-image-313" title="todocellh" src="/wp-content/uploads/2008/09/todocellh1.png" alt="" width="403" height="292" /></a></p>
<p style="text-align: left;">Let&#8217;s take this line by line&#8230;</p>
<p style="text-align: left;">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.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/datasample1.png"><img class="alignnone size-full wp-image-314" title="datasample" src="/wp-content/uploads/2008/09/datasample1.png" alt="" width="320" height="45" /></a></p>
<p style="text-align: left;">We see the &#8220;Green Dot&#8221; which is an image being rendered by a UIImageView.  The word &#8220;low&#8221; and &#8220;Take out the trash&#8221; 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&#8217;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.</p>
<p style="text-align: left;">Below this are some method declarations.  First we see the method &#8220;imageForPriority&#8221;.  We will be using this method to decide which image (green, red, yellow) gets displayed for a given priority.  Next, we see the &#8220;getter and setter&#8221; methods for the todo object.  As I explained above, the setter will contain additonal code besides assigning the todo object.</p>
<p style="text-align: left;">Now open up <strong>TodoCell.m</strong>.  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:</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/todocellm11.png"><img class="alignnone size-full wp-image-316" title="todocellm1" src="/wp-content/uploads/2008/09/todocellm11.png" alt="" width="485" height="344" /></a></p>
<p style="text-align: left;">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.</p>
<p style="text-align: left;">Looking at the initialize method&#8230;  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&#8230; 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)</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/todocellm21.png"><img class="size-full wp-image-317 aligncenter" title="todocellm2" src="/wp-content/uploads/2008/09/todocellm21.png" alt="" width="500" height="292" /></a></p>
<p style="text-align: left;">This is the initialiazation method for any UITableViewCell.  First, we need to call the super classe&#8217;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.</p>
<p style="text-align: left;">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.</p>
<p style="text-align: left;">Following this, we initialize the todoTextLabel.  This label will display what it is we need &#8220;to do&#8221; such as &#8220;Take out the trash&#8221;.  There is a method that we will be calling called &#8220;newLabelWithPrimaryColor&#8221;.  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&#8217;s &#8220;Seismic XML&#8221; sample code.  It&#8217;s pretty handy.  After this gets called, we simply add the new label to our view and these steps get repeated for the todoPriorityLabel.</p>
<p style="text-align: left;">Finally, the method &#8220;bringSubviewToFront&#8221; 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.  <strong>You can use this for layering your UI components.</strong></p>
<p style="text-align: left;">Still with me?  Good&#8230; now let&#8217;s add the following &#8220;getter&#8221; and &#8220;setter&#8221; methods for the todo object.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/todocellm31.png"><img class="size-full wp-image-318 aligncenter" title="todocellm3" src="/wp-content/uploads/2008/09/todocellm31.png" alt="" width="492" height="388" /></a></p>
<p style="text-align: left;">The first method todo is simple.  All it does is return our todo object.  The setTodo is a little more involved&#8230;</p>
<p style="text-align: left;">First, we set the incoming (newTodo) to our classe&#8217;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&#8217;t know what a switch statement is <a href="switch statement" target="_blank">Google it</a>.  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.</p>
<p style="text-align: left;">Now, let&#8217;s add the code that lays out the cell.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/todocellm41.png"><img class="size-full wp-image-319 aligncenter" title="todocellm4" src="/wp-content/uploads/2008/09/todocellm41.png" alt="" width="500" height="432" /></a></p>
<p style="text-align: left;">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.</p>
<p style="text-align: left;">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.</p>
<p>We have one more method to override.  It&#8217;s the setSelected method.  Go ahead and add the following code.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/todocellm51.png"><img class="size-full wp-image-321 aligncenter" title="todocellm5" src="/wp-content/uploads/2008/09/todocellm51.png" alt="" width="380" height="276" /></a></p>
<p style="text-align: left;">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.</p>
<p style="text-align: left;">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.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/todocellm61.png"><img class="size-full wp-image-322 aligncenter" title="todocellm6" src="/wp-content/uploads/2008/09/todocellm61.png" alt="" width="500" height="402" /></a></p>
<p style="text-align: left;"><strong>newLabelWithPrimaryColor</strong></p>
<p>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.</p>
<p><strong><span style="color: #888888;">imageForPriority</span></strong></p>
<p>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 &#8220;case 1&#8243; 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.</p>
<p>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.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/rootviewcontrollerm11.png"><img class="size-full wp-image-323 aligncenter" title="rootviewcontrollerm1" src="/wp-content/uploads/2008/09/rootviewcontrollerm11.png" alt="" width="130" height="18" /></a></p>
<p style="text-align: left;">Now find the numberOfRowsInSection method and add the following code</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/rootviewcontrollerm21.png"><img class="size-full wp-image-324 aligncenter" title="rootviewcontrollerm2" src="/wp-content/uploads/2008/09/rootviewcontrollerm21.png" alt="" width="500" height="52" /></a></p>
<p style="text-align: left;">I&#8217;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.</p>
<p>Now for the magic&#8230;We will now add our TodoCell to allow it to be displayed.  Find the cellForRowAtIndexPath method and add the following code.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/rootviewcontrollerm31.png"><img class="size-full wp-image-325 aligncenter" title="rootviewcontrollerm3" src="/wp-content/uploads/2008/09/rootviewcontrollerm31.png" alt="" width="500" height="194" /></a></p>
<p style="text-align: left;">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&#8217;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&#8217;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.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/09/screenshot2.png"><img class="alignnone size-full wp-image-327" title="screenshot" src="/wp-content/uploads/2008/09/screenshot2.png" alt="" width="386" height="742" /></a></p>
<p style="text-align: left;">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&#8217;t seen yet. As always, post your questions and comments in the comments section of the blog. <a href="/wp-content/uploads/2008/09/todo-part-211.zip">Download The Sample Code</a></p>
<p>Happy iCoding!</p>
]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2008/09/02/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-2/feed/</wfw:commentRss>
		<slash:comments>111</slash:comments>
		</item>
		<item>
		<title>iPhone Programming Tutorial &#8211; Creating a ToDo List Using SQLite Part 1</title>
		<link>http://icodeblog.com/2008/08/19/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-1/</link>
		<comments>http://icodeblog.com/2008/08/19/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-1/#comments</comments>
		<pubDate>Tue, 19 Aug 2008 17:46:15 +0000</pubDate>
		<dc:creator><![CDATA[brandontreb]]></dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[iphone programming]]></category>
		<category><![CDATA[iphone tutorial]]></category>
		<category><![CDATA[SQLite]]></category>
		<category><![CDATA[uitableview]]></category>
		<category><![CDATA[xcode]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=257</guid>
		<description><![CDATA[
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  ...]]></description>
				<content:encoded><![CDATA[<p><script type="text/javascript"><!--
digg_url = 'http://digg.com/apple/iPhone_Programming_Tutorial_Create_ToDo_List_Using_SQLite';
// --></script><script src="http://digg.com/api/diggthis.js"></script></p>
<p>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&#8217;t use them to create something useful.</p>
<p>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 <a href="/2008/08/08/iphone-programming-tutorial-populating-uitableview-with-an-nsarray/">fruits tutorial</a> and it&#8217;s prerequisites.</p>
<p>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:</p>
<ul>
<li><a href="#nav-based">Create a NavigationBased Application</a></li>
<li><a href="#create-db">Create a Database</a></li>
<li><a href="#add-db">Add the Database to Your Project</a></li>
<li><a href="#sqlite3-framework">Add the SQLite3 Framework</a></li>
<li><a href="#todo-object">Create a Todo Class Object</a></li>
<li><a href="#init-db">Initialize the Database</a></li>
</ul>
<p>So let&#8217;s get started&#8230;</p>
<h2><a name="nav-based"></a></h2>
<p>Open up X-Code and Select <strong>File-&gt;New Project&#8230; </strong>Select <strong>Navigation-Based Application</strong> and click <strong>Choose&#8230;</strong></p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/08/01navigationbased1.png"><img class="size-full wp-image-198 aligncenter" title="01navigationbased" src="/wp-content/uploads/2008/08/01navigationbased1.png" alt="" width="500" height="368" /></a></p>
<p style="text-align: left;">Name your project <strong>todo</strong>.  Now let&#8217;s create the todo database that we will be using.  Open up the <strong>Terminal</strong> application on your Mac.  This is located in <strong>Applications &gt; Utilities.</strong></p>
<h2 style="text-align: left;"><a name="create-db"></a></h2>
<p>If you have installed XCode, you should have mysqlite3 already on your computer.  To check this, type:</p>
<p style="text-align: left;"><code>sqlite3</code> into the Terminal and sqlite3 should start.  Type <code>.quit</code> to exit.  If sqlite3 is not installed, install all of the <strong>XTools</strong> from your <strong>Mac Installation Disk</strong>.</p>
<p style="text-align: left;">Now that the terminal is open let&#8217;s create the database. This is done with the command:</p>
<p style="text-align: left;">sqlite3 todo.sqlite</p>
<p style="text-align: left;">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 <a href="http://www.google.com/search?q=sql+tutorial&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t&amp;rls=org.mozilla:en-US:official&amp;client=firefox-a">Google It.</a> 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:</p>
<p style="text-align: left;"><code>CREATE TABLE todo(pk INTEGER PRIMARY KEY, text VARCHAR(25), priority INTEGER, complete BOOLEAN);</code></p>
<p style="text-align: left;">One thing to note here is the <strong>pk</strong> 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.</p>
<p style="text-align: left;">Now that our table has been created, let&#8217;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.</p>
<p style="text-align: left;"><code>INSERT INTO todo(text,priority,complete) VALUES('Take out the trash',3,0);<br />
INSERT INTO todo(text,priority,complete) VALUES('Do Computer Science homework',1,0);<br />
INSERT INTO todo(text,priority,complete) VALUES('Learn Objective C',1,0);<br />
INSERT INTO todo(text,priority,complete) VALUES('DIGG this tutorial',2,0);</code></p>
<p style="text-align: left;">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&#8217;ll see why later).  Now our database has been created and populated let&#8217;s exit out of SQLite3.  Do this by typing .quit.  Your terminal window should look something like this.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/08/1-deb-creation1.png"><img class="size-full wp-image-272 aligncenter" title="1-db-creation" src="/wp-content/uploads/2008/08/1-deb-creation1.png" alt="" width="500" height="272" /></a></p>
<h2 style="text-align: left;"><a name="add-db"></a></h2>
<p>Now go back to XCode.  Do a Control-Click (right click) on the folder named <strong>Resources</strong>. Click <strong>Add -&gt; Existing Files&#8230;</strong> and browse to your todo.sqlite file and click <strong>Add</strong>.  It will then prompt you with a screen like this.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/08/2-add-db1.png"><img class="size-full wp-image-259 aligncenter" title="2-add-db" src="/wp-content/uploads/2008/08/2-add-db1.png" alt="" width="400" height="374" /></a></p>
<p style="text-align: left;">Make sure you check the box that says <strong>Copy items into destination group&#8217;s folder (if needed).</strong> You should now see the todo.sqlite file inside of the resource folder.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/08/3-db1.png"><img class="size-full wp-image-260 aligncenter" title="3-db" src="/wp-content/uploads/2008/08/3-db1.png" alt="" width="188" height="324" /></a></p>
<h2 style="text-align: left;"><a name="sqlite3-framework"></a></h2>
<p>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 <strong>Frameworks </strong>folder.  Click <strong>Add -&gt; Existing Frameworks</strong>.  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 <strong>libsqlite3. </strong>The file we are looking for is called <strong>libsqlite3.0.dylib.</strong> This may pull up multiple files as OSX has it&#8217;s own versions of this file.  Just click on the largest of the files that show up and click <strong>Add.</strong> As you can see, mine is about 1.7 MB.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/08/4-framework1.png"><img class="size-full wp-image-261 aligncenter" title="4-framework" src="/wp-content/uploads/2008/08/4-framework1.png" alt="" width="500" height="371" /></a></p>
<p style="text-align: left;">Now it should add the framework and your directory will look something like this:</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/08/5-frameworkin1.png"><img class="size-full wp-image-262 aligncenter" title="5-frameworkin" src="/wp-content/uploads/2008/08/5-frameworkin1.png" alt="" width="174" height="85" /></a></p>
<h2 style="text-align: left;"><a name="todo-object"></a></h2>
<p>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 <strong>File -&gt; New File&#8230;</strong> Select <strong>NSObject Subclass</strong> and click <strong>Next.</strong></p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/08/6-object1.png"><img class="size-full wp-image-263 aligncenter" title="6-object" src="/wp-content/uploads/2008/08/6-object1.png" alt="" width="500" height="368" /></a></p>
<p style="text-align: left;">Name this object <strong>todo.m</strong> and check the box that says <strong>Also create &#8220;Todo.h&#8221;</strong> and click <strong>Finish.</strong></p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/08/7-addobject1.png"><img class="size-full wp-image-264 aligncenter" title="7-addobject" src="/wp-content/uploads/2008/08/7-addobject1.png" alt="" width="500" height="368" /></a></p>
<p style="text-align: left;">Open up <strong>todo.h</strong> and add the following code.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/08/8-todoh1.png"><img class="size-full wp-image-265 aligncenter" title="8-todoh" src="/wp-content/uploads/2008/08/8-todoh1.png" alt="" width="382" height="227" /></a></p>
<p style="text-align: left;">We see some new things here&#8230;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&lt;sqlite3.h&gt; in your imports.</p>
<p style="text-align: left;">Next, we see a primary key.  Notice that in the property declaration it has the keywords <strong>assign</strong> and <strong>readonly</strong>.  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.</p>
<p style="text-align: left;">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.</p>
<p style="text-align: left;">Let&#8217;s implement this method&#8230;Open up <strong>todo.m</strong> and add the following code.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/08/9-todom1.png"><img class="size-full wp-image-266 aligncenter" title="9-todom" src="/wp-content/uploads/2008/08/9-todom1.png" alt="" width="500" height="369" /></a></p>
<p style="text-align: left;">There are quite a few new things that need to be explained here.  I will just go through it line by line.</p>
<p style="text-align: left;"><code>static sqlite3_stmt *init_statement = nil</code></p>
<p style="text-align: left;">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&#8217;ll explain more  in a bit.</p>
<p style="text-align: left;">The next lines makes sure that the super class (NSObject) initilizes properly before we initilize a todo object.  We then set the local <strong>primary key</strong> and <strong>database</strong> objects to the parameters passed to the initWithPrimaryKey method.</p>
<p style="text-align: left;">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 <strong>if statement</strong> just checks to see if this finished correctly and prints an error if there was a problem.</p>
<p style="text-align: left;">Moving on&#8230; 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:</p>
<p style="text-align: left;"><code>SELECT text FROM todo WHERE pk = 1;<br />
SELECT text FROM todo WHERE pk = 2;<br />
SELECT text FROM todo WHERE pk = 3;<br />
SELECT text FROM todo WHERE pk = n;</code></p>
<p style="text-align: left;">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:</p>
<p style="text-align: left;"><code>self.text = [NSString stringWithUTF8String:(char*) sqlite3_column_text(init_statement,0)];</code></p>
<p style="text-align: left;">Wow, that&#8217;s a mouthful&#8230; Let&#8217;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&#8230;) so there is only 1 index and that&#8217;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.</p>
<p style="text-align: left;">This is quite a bit to explain in just text.  If I have lost you, feel free to ask me questions in the comments.</p>
<p style="text-align: left;">We are done with the todo object for now&#8230;</p>
<h2 style="text-align: left;"><a name="init-db"></a></h2>
<p>Go ahead and open up <strong>todoAppDelegate.h</strong> and add the following code.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/08/10-app-delegate1.png"><img class="size-full wp-image-267 aligncenter" title="10-app-delegate" src="/wp-content/uploads/2008/08/10-app-delegate1.png" alt="" width="466" height="244" /></a></p>
<p style="text-align: left;">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 <a href="/2008/08/08/iphone-programming-tutorial-populating-uitableview-with-an-nsarray/">fruit example</a>) 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 <strong>sqlite3.h</strong> and the <strong>sqlite3 *database </strong>line<strong>.</strong> Now let&#8217;s open up <strong>todoAppDelegate.m</strong> and add some code.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/08/11-appdelegatem-11.png"><img class="size-full wp-image-268 aligncenter" title="11-appdelegatem-1" src="/wp-content/uploads/2008/08/11-appdelegatem-11.png" alt="" width="285" height="202" /></a></p>
<p style="text-align: left;">One new thing we see here is a private interface.  We declared it here because it&#8217;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&#8217;s SQLBooks tutorial.  I will going through this code and explaining it the best that I can. Add the following code.</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/08/12-appdelegatem-21.png"><img class="size-full wp-image-269 aligncenter" title="12-appdelegatem-2" src="/wp-content/uploads/2008/08/12-appdelegatem-21.png" alt="" width="499" height="186" /></a></p>
<p style="text-align: left;">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&#8217;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&#8217;ll do a line-by-line writup of this function.</p>
<p style="text-align: left;">The next function we will implement is <strong>initializeDatabase. </strong>Add the following code:</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/08/13-appdelegatem-31.png"><img class="size-full wp-image-270 aligncenter" title="13-appdelegatem-3" src="/wp-content/uploads/2008/08/13-appdelegatem-31.png" alt="" width="500" height="398" /></a></p>
<p style="text-align: left;">That&#8217;s a lot of text! Don&#8217;t worry it&#8217;s mostly comments.  Let&#8217;s analyze this code&#8230;Some of it is very similar to the fruits example.</p>
<p style="text-align: left;">The first line creates and initializes a <strong>NSMutableArray</strong>.  We then go on to set this array to our object&#8217;s todos array and release the temporary object.</p>
<p style="text-align: left;">The next 3 lines locate the database we created inside of the documents folder.  Following that, the <strong>sqlite3_open</strong> line open&#8217;s the database so we can access its data.  If the database opens correctly, we then proceed to retrieve todo items.  The first line:</p>
<p style="text-align: left;"><code>const char *sql = "SELECT pk FROM todo";</code></p>
<p style="text-align: left;">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 <strong>todo.m</strong> file) only this time there is no &#8220;?&#8221; in the statement.  That is because there is not condition for retrieving the primary keys.  We are simply saying &#8220;give me all of the primary keys in the database&#8221;.</p>
<p style="text-align: left;">Now we see a <strong>while loop</strong> that is stepping through the SQL results.  Every time we call <strong>sqlite3_step</strong>, the next result gets retrieved.  The line:</p>
<p style="text-align: left;"><code>int primaryKey = sqlite3_column_int(statement,0);</code></p>
<p style="text-align: left;">retrieves the primary key from each result.  This is very similar to retrieving the text in the <strong>todo.m</strong> class only  we use the <strong>sqlite3_column_int</strong> method instead of the <strong>sqlite3_column_text</strong> method.  This is done for obvious reasons.</p>
<p style="text-align: left;">After we have the primary key, we create a new Todo object and call the <strong>initWithPrimaryKey</strong> constructor that we created.  The primary key gets passed as well as a reference to the database.  This allows the Todo object to essentially &#8220;look itself up&#8221; in the database.  Finally, we add the newly created Todo object to our array of todos.</p>
<p style="text-align: left;">The last statement <strong>sqlite3_finalize</strong> clears the statement from memory and does some other cleanup.</p>
<p style="text-align: left;">The last part of this tutorial is calling these functions to create and initialize the database.  So add the following code to applicationDidFinishLaunching:</p>
<p style="text-align: center;"><a href="/wp-content/uploads/2008/08/14-appdelegatem-41.png"><img class="size-full wp-image-271 aligncenter" title="14-appdelegatem-4" src="/wp-content/uploads/2008/08/14-appdelegatem-41.png" alt="" width="425" height="131" /></a></p>
<p style="text-align: left;">We are simply calling these functions.  You can now click <strong>Build and Go</strong> but your application won&#8217;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.</p>
<p style="text-align: left;">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.</p>
<p style="text-align: left;">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 <a href="/wp-content/uploads/2008/08/todo-part-11.zip">here</a></p>
<p style="text-align: left;">Happy iCoding!</p>
<p style="text-align: left;">
]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2008/08/19/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-1/feed/</wfw:commentRss>
		<slash:comments>233</slash:comments>
		</item>
	</channel>
</rss>
