Clicky

iOS Dev Nugget 302 Realm

.

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

Most apps need some kind of backing datastore and sometimes plist(s) are a perfectly fine option. When you need to handle more, structured data, you can consider SQLite, perhaps with a wrapper like FMDB. Alternatively, there is Realm which provides a local database and an optional cloud-sync service.

It's easy to get started, especially if you just want to use it for local storage.

Add it to your Podfile:

pod 'RealmSwift'

Install:

$ pod install --repo-update

Import the framework:

import RealmSwift

Define a class that is backed by Realm:

class Item: Object {
    @objc dynamic var itemId: String = UUID().uuidString
    @objc dynamic var body: String = ""
    @objc dynamic var timestamp: Date = Date()

    override static func primaryKey() -> String? {
        return "itemId"
    }
}

The properties that you want stored in Realm has to be declared with @objc and dynamic.

Create the database instance:

let realm = try! Realm()

Fetch objects:

items = realm.objects(Item.self).sorted(byKeyPath: "timestamp", ascending: false)

Create and save a new object:

try! realm.write {
    realm.add(item)
}

Update an object:

try! realm.write {
    item.body = "Something something"
}

Delete an object:

try! realm.write {
    realm.delete(item)
}

You can define parent-child relationships:

class Parent: Object {
    @objc dynamic var parentId: String = UUID().uuidString
    var items = List<Item>()

    override static func primaryKey() -> String? {
        return "parentId"
    }
}

You can perform schema migrations with a migration block:

config.migrationBlock = { migration, oldSchemaVersion in
    if oldSchemaVersion < 10 {
        migration.enumerateObjects(ofType: Item.className()) { oldObject, newObject in
            guard let oldObject = oldObject else { return }
            guard let newObject = newObject else { return }
            newObject["someChangedVarName"] = oldObject["oldChangedVarName"]
        }
    }

    if oldSchemaVersion < 20 {
        //...
    }
}

It's extremely quick to start and low effort to use for local storage.

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