Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Creating an Objective-C interface for SQLite

From: iOS SDK and SQLite: Building Data-Driven Apps

Video: Creating an Objective-C interface for SQLite

The native SQLite interface is written in C, and while it works very well, it's not very convenient in an Objective-C environment. So, we will begin by writing a wrapper, which is sometimes called an Adapter Pattern, to encapsulate the C Language SQLite interface in a native Objective-C interface that's easy to use and to extend for our purposes. So first, let's take a look at what we want this interface to accomplish. I'm just going to open this BWDB-testbed-code.txt, in my text editor, I'm using TextWrangler here.

Creating an Objective-C interface for SQLite

The native SQLite interface is written in C, and while it works very well, it's not very convenient in an Objective-C environment. So, we will begin by writing a wrapper, which is sometimes called an Adapter Pattern, to encapsulate the C Language SQLite interface in a native Objective-C interface that's easy to use and to extend for our purposes. So first, let's take a look at what we want this interface to accomplish. I'm just going to open this BWDB-testbed-code.txt, in my text editor, I'm using TextWrangler here.

You can use whatever editor you like just make sure it's a real plain text editor and not a Word Processor. So, you'll notice here is the testDatabase function. And this is the method that I'm going to be using to test this database interface, and so it shows how the interface is called. And really my goal was to have an interface that works like this. So for instance, I can have something, that you know, sends a message to the db object that says doQuery and in a string it has an SQL query "drop table if it exists", CREATE TABLE with this schema, insert into table, values this and that, and you notice that there are place markers and then there are various values.

These are actually Objective-C objects that are used as arguments. And so, my interface has to support what we call variadic arguments in C-based languages. And so, with variadic arguments I can have as many, or as few, of these arguments as I like after the string that has the format in it, and specifies how many arguments I'm going to actually be needing. My interface also allows me to do something like this for row in and then I have this expression here that calls this method getQuery on the db object and has a query in it.

And so, what that will do is it will actually go through the database and get one row at a time and pass those rows off into this row variable and allow me to operate on that. It's a very convenient syntax for calling, and it's accomplished in Objective-C with a protocol called NSFastEnumeration, and we'll see how that's done as well. We also have these CRUD-based methods where I can do something like insertRow and then have a dictionary. This is a literal dictionary using the new Objective-C literal syntax.

And I can just pass it a dictionary object, and it will insert that row into a table that has already been specified in the constructor. So, I have CRUD insert, here is a CRUD update and here is a CRUD delete. So, that's how we want to be able to use this. Let's go ahead and create an interface that will do exactly this. We're going to start by navigating to the Chapter02 folder in the exercise files. And we're going to make a working copy of Testbed.

I'm just going to press Command+C on this Mac and select my folder and press Command+V, and that will allow me to make a working copy here. And I'm going to call this Testbed-02-working, and I'm going to open it up by navigating to the Xcode project file inside of that folder and double-clicking. So, this is actually our finished Testbed from the previous chapter. You notice if I select the iPhone Simulator and press Run, it will build, and it will run it in the iPhone Simulator.

And you can see this is exactly the same Testbed that we had in the last chapter. So, I'm going to come back over here to Xcode, I'm going to press Command+Period to stop these simulators, here it says Finished running the simulator. Now, we're going to select the target, so we select Testbed up here in the top of the Project navigator. And then, I will select Target over here and Summary over here, and scroll down for a while, and you see we have these Linked Frameworks. We're going to add a framework for our SQLite here.

So, I'm going to press the plus button, and I'm going to type, sqlite in the Search there, sql was enough. I'm going to select sqlite 3. dynamic library and click Add. And now, you'll notice that there it is in our frameworks, and we've added the sqlite.dylib to our Link Frameworks. And then down here in our Testbed files, we want to add our database library. So, I've got a library called BWDB in the exercise files.

So, we come back out here in the exercise files and select Libraries, and just grab the BWDB folder. You'll notice inside that folder there are just a couple of files: a .m file and a .h file. We'll take a look at those in a little bit here. So, we're going to grab this whole folder, and we're going to bring it over here until Testbed is highlighted. You see, you can highlight different things here, and you want to highlight Testbed in the folder version of it there, and it will then drop that in right there. Brings up this dialog box, you want to select Copy items, Create groups, and Add to targets for Testbed, and Finish.

And so, it copies those files, it creates a group for them called BWDB, and there are the files, there's the m file which is the implementation and the h file which is the header file. Let's just take a quick look here. The header file has our interface, you notice it I reads in the sqlite3.h header file from the SQLite 3 Framework that we imported earlier. And you'll notice down here, we have our actual interface. We have a constructor with Filename, a constructor with a Filename and a TableName that's used for the CRUD methods.

We have an openDB, closeDB, a d structure-- dealloc is a d structure--and it basically just closes the database. We have Fast enumeration support. That allows us to do that trick where we put the object in an enumeration for loop. We have SQL queries, doQuery, getQuery, prepareQuery, valueFromQuery. And you notice these have the variadic arguments. If you want to know more about variadic arguments in C-based languages, you can take a look at my C and C++ Essential Training on the lynda.com online training library.

These raw results are pretty much just used internally to translate these variadic queries into something that will return a value. And then, here we have the CRUD methods. This is the heart and soul of this. We can insert a row, update a row, delete a row, get a row, and count rows. And we also have Subscripting methods that support the new keyed subscripts that are available in the latest version of Objective-C. This is all implemented in our .m file and just briefly we're not going to go through this in a lot of detail.

You've got the source code here, and you're welcome to look through it and modify it and use it in whatever way you like. Our constructors simply set up the file name and open the database. And they call this openDB, which goes through a little bit of trouble to actually find the database file in the iPhone iOS file system. An SQLite database is kept entirely in one flat file, all the tables in a given database are all in one very portable file, which is why SQLite is used on so many mobile platforms.

closeDB simply calls SQLite 3 to close, that's the C interface for SQLite 3 and dealloc simply calls closeDB. Here is the Fast enumeration support. There's very little documentation in the Apple documentation of Objective-C as to how fast enumeration works. Basically they give you some examples, and you can play around with those examples until you get something to work, which is what I did here. Here is our basic doQuery, which you'll notice uses variadic arguments here and here is the va_list and va_start for the variadic arguments.

And you'll notice that it uses the SQLite C interface, sqlite3_step, sqlite3_finalize, sqlite3_changes. And again, prepareQuery is very simple, getQuery is likewise simple, as is valueFromQuery. bindSQL is where a lot of the work is done. This actually introspects the arguments, the objects that are passed in the variadic list using respondsToSelector to figure out what the type is of the argument and to call the appropriate sqlite3_bind_int, double sqlite3_ bind_text in order to interface with SQLite.

Our raw results here are used mostly internally within the BWDB class. And these are our CRUD methods, this is for inserting a row. InsertRow uses some string methods in order to construct a sql query to insert the row into the database. Likewise, updateRow constructs an sql query for updating a row in the table. deleteRow and getRow are very straightforward, because how you do that in SQL is very straightforward.

And likewise, these Keyed Subscripting Methods are also very simple. And then we have a couple of simple Utility Methods for getting a call in value in getting the lastInsertId. So, you can see that the value of the wrapper is in its ability to hide the complexity of the native SQLite interface from the Objective-C implementation. The C Language interface for SQLite is full-featured, but it's cumbersome. And when we finish the Testbed implementation using this wrapper, we'll get a good idea of just how much easier it is to use this in Objective-C.

Show transcript

This video is part of

Image for iOS SDK and SQLite: Building Data-Driven Apps
iOS SDK and SQLite: Building Data-Driven Apps

41 video lessons · 6523 viewers

Bill Weinman
Author

 
Expand all | Collapse all
  1. 8m 29s
    1. Welcome
      57s
    2. Exercise files
      2m 17s
    3. Course overview
      3m 4s
    4. Application overview
      2m 11s
  2. 14m 49s
    1. Prototyping in a testbed
      1m 27s
    2. Building the view controller
      3m 45s
    3. Coding the testbed
      7m 56s
    4. Using the testbed
      1m 41s
  3. 37m 49s
    1. Understanding SQLite in iOS
      1m 41s
    2. Creating an Objective-C interface for SQLite
      9m 57s
    3. Testing the BWDB interface in the sandbox
      7m 1s
    4. Designing a database schema
      8m 7s
    5. Supporting the application with a specific interface
      7m 7s
    6. Using C pointers with automatic reference counting (ARC)
      3m 56s
  4. 21m 18s
    1. Understanding the table view
      1m 33s
    2. Creating the view controller
      6m 39s
    3. Reading from the database
      13m 6s
  5. 33m 50s
    1. Understanding the parsing process
      1m 57s
    2. Creating the item view controller
      12m 25s
    3. Reading data from the internet
      5m 30s
    4. Parsing the feed with NSXMLParser
      8m 2s
    5. Updating the item view with the feed items
      5m 56s
  6. 40m 14s
    1. Understanding the modal view
      1m 47s
    2. Constructing the view controller
      15m 5s
    3. Finding a feed link in a web page
      8m 55s
    4. Parsing the feed with NSXMLParser
      5m 4s
    5. Delegating back to the parent view
      6m 11s
    6. Deleting feeds
      3m 12s
  7. 21m 5s
    1. Creating the web view class
      12m 33s
    2. Coding the web view
      5m 25s
    3. Viewing pages in Safari
      3m 7s
  8. 14m 3s
    1. Understanding the iOS preferences system
      1m 23s
    2. Creating the preferences plist in Xcode
      7m 20s
    3. Reading preferences in your application
      5m 20s
  9. 6m 15s
    1. Adding pull-to-refresh functionality
      2m 34s
    2. Implementing the pull-to-refresh gesture for iOS 6
      3m 41s
  10. 27m 1s
    1. Understanding split view
      1m 4s
    2. Coding the table views
      11m 24s
    3. Implementing the iPad detail view
      6m 35s
    4. Implementing the iPad modal view
      7m 58s
  11. 35s
    1. Goodbye
      35s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed iOS SDK and SQLite: Building Data-Driven Apps.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.