Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Realm iOS

Avatar for eenwak eenwak
March 16, 2017

Realm iOS

Talk given at CocoaHeads Strasbourg

Avatar for eenwak

eenwak

March 16, 2017

Other Decks in Programming

Transcript

  1. Source: Realm (15 septembre 2014) queries per seconds Counts Get

    counts of records matching a query on a databse of 200k records (higher is be;er) SQLite libraries Realm SQLite FMDB Core Data Couchbase Lite YapDatabase 0.066 0.069 1 13.6 13.6 30.9 40 30 20 10 0
  2. Source: Realm (15 septembre 2014) queries per seconds Queries Iterate

    over all records matching a query (higher is be9er) SQLite libraries Realm SQLite FMDB Core Data Couchbase Lite YapDatabase 0.06 0.07 2 13 14 31 40 30 20 10 0
  3. Source: Realm (15 septembre 2014) records inserted per seconds Inserts

    Insert 200K records, in a single transac4on (higher is be8er) SQLite libraries SQLite Realm FMDB Core Data YapDatabase Couchbase Lite 1.7K 5.1K 18K 47K 94K 178K 180K 135K 90K 45K 0K
  4. Subclass Object class Dog: Object { dynamic var name =

    "" dynamic var owner: Person? } …and that’s it.
  5. RelaConships To-One To-Many Inverse class Dog: Object { // to-one

    relationships must be optional dynamic var owner: Person? }
  6. RelaConships To-One To-Many Inverse class Dog: Object { dynamic var

    name = "" dynamic var age = 0 let owners = LinkingObjects(fromType: Person.self, property: "dogs") }
  7. Create / Add var myDog = Dog() myDog.name = "Rex"

    myDog.age = 10 // Add to realm try! realm.write { realm.add(author) } // Create using dictionary let myOtherDog = Dog(value: ["name" : "Pluto", "age": 3])
  8. Update // … try! realm.write { realm.add(cheeseBook, update: true) }

    // … try! realm.write { realm.create(Book.self, value: ["id": 1, "price": 9000.0], update: true) }
  9. Filter var whiteDogs = realm.objects(Dog.self) .filter("color = 'white'") using predicates

    let predicate = NSPredicate(format: "color = %@“, "white") whiteDogs = realm.objects(Dog.self).filter(predicate)
  10. Sort let sortedDogs = realm.objects(Dog.self) .sorted(byKeyPath: "name") let dogOwners =

    realm.objects(Person.self) let ownersByDogAge = dogOwners.sorted(byKeyPath: "dog.age")
  11. func readPagesCount() -> Int { let predicate = NSPredicate(format: "statusValue

    == %d", BookStatus.finished.rawValue) return realm.objects(Book).filter(predicate).sum("pages") } func readPagesCount() -> Int { let predicate = NSPredicate(format: "statusValue == %d", BookStatus.FINISHED.rawValue) let expressionDesc = NSExpressionDescription() expressionDesc.name = "sumOfPages" expressionDesc.expression = NSExpression(forFunction: "sum:", arguments:[NSExpression(forKeyPath: "pages")]) expressionDesc.expressionResultType = .StringAttributeType var totalPages: Float = 0 let fetchRequest = NSFetchRequest(entityName: entityName) fetchRequest.propertiesToFetch = [expressionDesc] fetchRequest.resultType = .DictionaryResultType fetchRequest.predicate = predicate do { var results = try coreDataController.managedObjectContext?.executeFetchRequest(fetchRequest) if let dict = results![0] as? [String: String] { totalPages = Float(dict["sumOfPages"]!)! } } catch { fatalError("Failed to fetch data: \(error)") } return Int(totalPages) }
  12. It is possible to be noCfied whenever a Realm, a

    collecCon or an Object is updated.
  13. Realm // Observe Realm Notifications let token = realm.addNotificationBlock {

    (notification, realm) in viewController.updateUI() } // later token.stop()
  14. CollecCon let results = realm.objects(Person.self).filter("age > 5") let token =

    results.addNotificationBlock { changes in switch changes { case .initial: // … case .update(_, let deletions, let insertions, let modifications): // … case .error(let error): // … } }
  15. let token = stepCounter.addNotificationBlock { change in switch change {

    case .change(let properties): // … case .error(let error): // … case .deleted: // … } } Object
  16. Let’s migrate the Person model. class Person: Object { dynamic

    var firstName = "" dynamic var lastName = "" dynamic var age = 0 } class Person: Object { dynamic var fullName = "" dynamic var age = 0 }
  17. let config = Realm.Configuration( schemaVersion: 1, migrationBlock: { migration, oldSchemaVersion

    in if oldSchemaVersion < 1 {/* Updates go here */} }) Realm.Configuration.defaultConfiguration = config let realm = try! Realm() realm will detect the changes automa9cally Simple migraCon
  18. migration.enumerateObjects(ofType: Person.className) { oldObject, newObject in let firstName = oldObject!["firstName"]

    as! String let lastName = oldObject!["lastName"] as! String newObject!["fullName"] = "\(firstName) \(lastName)" } Modifying values
  19. let usernameCredentials = SyncCredentials.usernamePassword (username: "username", password: "password") let googleCredentials

    = SyncCredentials.google(token: "Google token") let facebookCredentials = SyncCredentials.facebook(token: "Facebook token") let cloudKitCredentials = SyncCredentials.cloudKit(token: "CloudKit token") AuthenCcaCon
  20. // Create the configuration let syncServerURL = URL(string: "realm://server:9080/~/userRealm")! let

    config = Realm.Configuration(syncConfiguration: SyncConfiguration(user: user, realmURL: syncServerURL)) // Open the remote Realm let realm = try! Realm(configuration: config) // Any changes made to this Realm will be synced across all devices ConfiguraCon