Realms - toant-dev/toandev.github.io GitHub Wiki

Why Use Realm

  • Object-Oriented
// Define your models like regular Swift classes
class Dog: Object {
    @objc dynamic var name = ""
    @objc dynamic var age = 0
}
class Person: Object {
    @objc dynamic var _id = ""
    @objc dynamic var name = ""
    @objc dynamic var age = 0
    // Create relationships by pointing an Object field to another Class
    let dogs = List<Dog>()
    
    override static func primaryKey() -> String? {
        return "_id"
    }
}
// Use them like regular Swift objects
let dog = Dog()
dog.name = "Rex"
dog.age = 1
print("name of dog: \(dog.name)")

// Get the default Realm
let realm = try! Realm()
// Persist your data easily with a write transaction 
try! realm.write {
    realm.add(dog)
}
  • Live Objects
// Open the default realm.
let realm = try! Realm()

var token: NotificationToken?

let dog = Dog()
dog.name = "Max"

// Create a dog in the realm.
try! realm.write {
    realm.add(dog)
}

//  Set up the listener & Observe object notifications.
token = dog.observe { change in
    switch change {
    case .change(let properties):
        for property in properties {
            print("Property '(property.name)' changed to '(property.newValue!)'");
        }
    case .error(let error):
        print("An error occurred: (error)")
    case .deleted:
        print("The object was deleted.")
    }
}

// Update the dog's name to see the effect.
try! realm.write {
    dog.name = "Wolfie"
}
  • Fully Encrypted
// Generate a random encryption key
val key = ByteArray(64)
SecureRandom().nextBytes(key)

// Set the encryption key in the config and open the realm
val config = RealmConfiguration.Builder()
    .encryptionKey(key)
    .build()

val realm = Realm.getInstance(config)

// Use the realm as normal
val dog = realm.where<Dog>().equalTo("name", "Fido").findFirst()
  • Fast Querying Lazy loading and a zero-copy architecture mean complex queries complete in microseconds.

  • Cross-Platform Use a single database to build all your apps, on any major platform. Mobile, desktop and IoT.

  • Open Source Realm is distributed under the Apache 2.0 license and backed by MongoDB.

  • Data Sync The MongoDB Realm Sync service makes it simple to keep data in sync across users, devices, and your backend in real-time.

Notifications

// Observe Realm Notifications
let token = realm.observe { notification, realm in
    viewController.updateUI()
}

// later
token.invalidate()

var token : NotificationToken?
token = stepCounter.observe { change in
    switch change {
    case .change(let object, let properties):
        for property in properties {
            if property.name == "steps" && property.newValue as! Int > 1000 {
                print("Congratulations, you've exceeded 1000 steps.")
                token = nil
            }
        }
    case .error(let error):
        print("An error occurred: \(error)")
    case .deleted:
        print("The object was deleted.")
    }
}

Migrations

// Inside your application(application:didFinishLaunchingWithOptions:)

let config = Realm.Configuration(
    // Set the new schema version. This must be greater than the previously used
    // version (if you've never set a schema version before, the version is 0).
    schemaVersion: 1,

    // Set the block which will be called automatically when opening a Realm with
    // a schema version lower than the one set above
    migrationBlock: { migration, oldSchemaVersion in
        // We haven’t migrated anything yet, so oldSchemaVersion == 0
        if (oldSchemaVersion < 1) {
            // Nothing to do!
            // Realm will automatically detect new properties and removed properties
            // And will update the schema on disk automatically
            
            // combine name fields into a single field
            let firstName = oldObject!["firstName"] as! String
            let lastName = oldObject!["lastName"] as! String
            newObject!["fullName"] = "\(firstName) \(lastName)"
            
            // The renaming operation should be done outside of calls to `enumerateObjects(ofType: _:)`.
            migration.renameProperty(onType: Person.className(), from: "yearsSinceBirth", to: "age")
        }
    })

// Tell Realm to use this new configuration object for the default Realm
Realm.Configuration.defaultConfiguration = config

// Now that we've told Realm how to handle the schema change, opening the file
// will automatically perform the migration
let realm = try! Realm()
⚠️ **GitHub.com Fallback** ⚠️