SQLite database has native support in iOS. The post provides a simple helper class that you can use to retrieve data and perform update operations on the data.

The helper class uses the libsqlite3.dylib library. Link the XCode project with the library. Create a helper class in Objective-C: DbHelper.

Header file

Define the DbHelper class with a static method (getInstance) to create a singleton instance. Add methods to execute a query (executeQuery) or command (executeCommand).

Moving the database to Caches Directory

The database is part of the application bundle. For querying the database, use it directly from the application bundle. For performing update operations, move the database to Library directory of the Application Sandbox.  Don’t move it to the Documents directory of the application sandbox. If the database is not created for the user.

Move it to the Caches sub-directory within the Library directory. The Caches directory is not backed up by iTunes. When there is a space constraint in the device, the system deletes the cache. But only when the application is not in use.

Call the method when the application loads.

Opening the database

Open the database in the init method of the helper class.

Implementing as Singleton

The helper object is implemented as a singleton.

Querying the Database

To execute queries on the database, use the executeQuery method. Querying the database will yield a statement object. The statement object has a cursor. Fill entity objects using the cursor.

Executing commands on the Database

To execute commands on the database, use the executeCommand method.

Create a statement object from a SQL query. Executes the statement object. And don’t forget to dispose the statement object.

We have completed our simple helper class which executes a query or command on the database.

Helper class for using SQLite database in iOS
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *