Skip to content

Instantly share code, notes, and snippets.

@reeichert
Created December 26, 2017 14:47
Show Gist options
  • Save reeichert/516de2349228bfcf087803b7a1b05a40 to your computer and use it in GitHub Desktop.
Save reeichert/516de2349228bfcf087803b7a1b05a40 to your computer and use it in GitHub Desktop.
Realm helper
import Foundation
import RealmSwift
var realmConfiguration: Realm.Configuration?
public typealias VoidCompletion = () -> Void
extension Realm {
static var shared: Realm? {
if let configuration = realmConfiguration {
return try? Realm(configuration: configuration)
} else {
let configuration = Realm.Configuration(
deleteRealmIfMigrationNeeded: true
)
return try? Realm(configuration: configuration)
}
}
static func execute(_ execution: @escaping (Realm) -> Void, completion: VoidCompletion? = nil) {
var backgroundTaskId: UIBackgroundTaskIdentifier?
backgroundTaskId = UIApplication.shared.beginBackgroundTask(withName: "reeichert.dev.realm.background", expirationHandler: {
backgroundTaskId = UIBackgroundTaskInvalid
})
if let backgroundTaskId = backgroundTaskId {
DispatchQueue.global(qos: .background).async {
guard let realm = self.shared else { return }
try? realm.write {
execution(realm)
}
DispatchQueue.main.async {
completion?()
}
UIApplication.shared.endBackgroundTask(backgroundTaskId)
}
}
}
static func executeOnMainThread(_ execution: @escaping (Realm) -> Void) {
guard let realm = self.shared else { return }
try? realm.write {
execution(realm)
}
}
// MARK: Mutate
// This method will add or update a Realm's object.
static func delete(_ object: Object) {
guard !object.isInvalidated else { return }
self.execute({ realm in
realm.delete(object)
})
}
// This method will add or update a Realm's object.
static func update(_ object: Object) {
self.execute({ realm in
realm.add(object, update: true)
})
}
// This method will add or update a list of some Realm's object.
static func update<S: Sequence>(_ objects: S) where S.Iterator.Element: Object {
self.execute({ realm in
realm.add(objects, update: true)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment