In previous articles we have utilized NSUserDefaults and .NET web services to persist iPhone data. NSUserDefaults is idol for storing small amounts of data. Web services are used to store the data on a custom server. In this article we will take a look at how to store iPhone data in SQLite database using FMDB wrapper.

FMDB:

The iOS SDK provides API for persisting data in the SQLite database. Unfortunately, the API is in pure C language which makes it hard for developers to use it.

FMDB is a wrapper on top of the base API and provides easy to use methods to perform database operations using Objective-C language. FMDB is an open source project which can be downloaded using the this link.

Once, FMDB is downloaded you can import the following files in your custom Group in your iOS application.

FMDBDatabase.h
FMDBDatabase.m
FMResultSet.h
FMResetSet.m

Also, make sure to add a link to the "libsqlite3.dylib" library. Compile the app and make sure it builds successfully. In the next section we are going to create our SQLite3 database.

Creating SQLite3 database:

You can easily use the Terminal to create the SQLite3 database. The screenshot below shows how a database named "Customers.db" is created and a single record is inserted into the "customers" table.


There are several plugins that allow to view and edit the information stored in the SQLite3 database. We recommend checking out the SQLite Manager FireFox plugin.

When you are done adding some custom rows to your newly created "Customers.db" database copy it into your "Supporting Files" or "Resources" folder. From there we will transfer the database file to the iPhone "Documents" folder. The advantage of copying the database into Documents folder is that it will be backed up whenever the iPhone is backed up. For iOS5 cloud enabled devices this means your database will be available on the cloud.

In the next section we will copy the SQLite3 database into iPhone "Documents" folder.

Copying Database to iPhone Documents Folder:

The AppDelegate is responsible for copying the database to the iPhone "Documents" folder. This operation is only performed when the database does not exists in the "Documents" folder. The implementation is shown below:

 

The NSFileManager is responsible for making sure that the database is not overridden if it already exists.

In the next section we are going to display the data in our view. The views and the application flow is created using Storyboards, new feature in iOS5 SDK.

Displaying Customers on UITableView:

The starting point of the app will be a UINavigationController which will display a UITableViewController. The UITableViewController will display the current customers to the user. We have implemented all the CRUD operations inside our custom file "FMDBDataAccess.m". The "FMDBDataAccess.h" header is implemented below:



The getCustomers method is implemented below:



The FMDatabase instance is responsible for connecting to the SQLite3 database using the path to the database. The FMResultSet is populated with the result of the SQL query. Finally, we loop through the rows and populate the Customer object and add it to the customers array. The populated customers array is returned to the caller.

NOTE: You should always use @try-@catch-@finally blocks when working with database connections and make sure the database connection is closed in the @finally block. This will ensure that the connection is closed even when an exception is thrown.

The getCustomers method is invoked from our CustomersViewController. The populateCustomers method is implemented below:



The populateCustomers is triggered from inside the viewDidLoad method. Finally, the cellForRowAtIndexPath is triggered which populates the tableView.



The screenshot below shows the customers populated on the UITableView.



In the next section we are going add new customers to the database.

Adding and Updating New Customers:

Before iOS 5 developers had to manager the flow of their screens using UINavigationController. iOS 5 introduced Storyboards which allows developers to use Storyboard designer to create all the workflows of the iOS application. To learn more about Storyboards check out the following articles on Ray Winderlech website:

1) Begining Storyboards
2) Intermediate Storyboards

The "+" button in the previous screenshot will take you to a different view which is composed of the static UITableView cells. The screenshot below shows the Add Customer screen.



The Add Customer view simply displays two UITextFields for first name and last name respectively. The user enters the required information and save the new customer by using the save button. The save button invokes the done method and triggers a delegate which passes the new customer to the CustomerViewController and then persist in the database.



The protocol declaration for the delegate is shown below:



The CustomerViewController handles the delegate and persist the new customer into the database. Make sure that the CustomerViewController adheres to the delegate as shown in the code below:



The didAddCustomer method is implemented in the CustomerViewController.m file as shown below:



The real persisting of data is performed in the FMDBDataAccess class. The insertCustomer method is responsible for saving a new customer to the database. The insertCustomer method is shown below:



The executeUpdate method executes the SQL statements which inserts the new customer in the database. The new customer is added to the UITableView inside the didAddCustomer implementation as shown below:



If you run the app you will notice that when you save nothing happens. This is because you need one additional step which is to prepare the segue between the different views. The implementation is shown below:



The "AddCustomer" and the "EditCustomer" constants are the unique identifiers of the segue. Now, if you run the above code and add a new customer you will notice that it shows up in the customers UITableView control.

The insert customer method was successful but now we need a way to edit/update the customer. The user can edit the customer once they click on the customer row. The customer row is linked to the add customer view we implemented earlier.

The selected customer is assigned to the customerToEdit property of the AddCustomerViewController instance as shown in the segue code below:

   

The AddCustomerViewController checks if the customerToEdit is nil or not. If it is not then it populates the first name and last name UITextFields with the information as shown in the code below:



The screenshot is shown below:



Now, when the user saves the current customer it will not be inserted but updated in the database. The "done" method makes sure not to insert the customer which is in edit state.



The didEditCustomer delegate is invoked which triggers the FMDBDataAccess updateCustomer method. The updateCustomer method is implemented below:



Try it out and edit a customer. Once, you save the customer you will notice the UITableView now displays the updated customer.

Resources:

1) Learning iOS Development Part 13 (Sqlite3 Using FMDB)

Conclusion:

In this article we demonstrated how to use FMDB API to make CRUD on SQLite3 database very simple for iOS development. 

[Download Sample]