Clicky

iOS Dev Nugget 143 Don't Forget SQLite

.

Need to run a code review on your codebase? Hire me

Between Core Data, serializing dictionaries and arrays into plists, and even NSUserDefaults, we sometimes forget about a very powerful tool we have at our disposal – SQLite.

I mentioned FMDB by (Gus Mueller as a simple way of accessing SQLite using Objective C.

There's now a number of handy Swift wrappers for Objective C including SQLite.swift by Stephen Celis. It provides a pure Swift interface so you can avoid writing raw SQL directly, at the same time offering direct access to the SQLite C API so you can drop down to SQL if you needed to.

An excellent example from the README:

import SQLite

let db = Database("path/to/db.sqlite3")

let users = db["users"]
let id = Expression<Int64>("id")
let name = Expression<String?>("name")
let email = Expression<String>("email")

db.create(table: users) { t in
    t.column(id, primaryKey: true)
    t.column(name)
    t.column(email, unique: true)
}
// CREATE TABLE "users" (
//     "id" INTEGER PRIMARY KEY NOT NULL,
//     "name" TEXT,
//     "email" TEXT NOT NULL UNIQUE
// )

var alice: Query?
if let rowid = users.insert(name <- "Alice", email <- "alice@mac.com").rowid {
    println("inserted id: \(rowid)")
    // inserted id: 1
    alice = users.filter(id == rowid)
}
// INSERT INTO "users" ("name", "email") VALUES ('Alice', 'alice@mac.com')


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues