Skip to content

Instantly share code, notes, and snippets.

@andresr-dev
Created June 2, 2023 17:37
Show Gist options
  • Save andresr-dev/dc7de3739c302615ba8c194cc07106a1 to your computer and use it in GitHub Desktop.
Save andresr-dev/dc7de3739c302615ba8c194cc07106a1 to your computer and use it in GitHub Desktop.
This is a Realm Manager class with all the CRUD operations in swift
import Foundation
import RealmSwift
class RealmManager {
/// Creates a `Realm` file in Documents directory
fileprivate var realm: Realm {
do {
return try Realm()
} catch let error {
let nsError = error as NSError
if nsError.code == 10 {
// The realm schema was modified, so delete the realm from disk and create a new one.
let defaultUrl = Realm.Configuration.defaultConfiguration.fileURL!
try! FileManager.default.removeItem(at: defaultUrl)
return self.realm
}
print("Default realm init failed: ", error)
fatalError("Realm couldn't be initialized.")
}
}
/// Fetch multiple `Object`s.
/// - Returns: The array of objects found.
func fetchObjects<T: Object>() -> [T] {
realm.objects(T.self).filter { !$0.isInvalidated }
}
/// Fetch a single `Object` with a given `primaryKey`.
/// - Parameter primaryKey: The primary key of the object to fetch.
/// - Returns: The `Object` found.
func fetchObject<T: Object, K: Hashable>(primaryKey: K) -> T? {
guard let object = realm.object(ofType: T.self, forPrimaryKey: primaryKey) else { return nil }
return !object.isInvalidated ? object : nil
}
/// Fetch a single `Object` with a given query predicate.
/// - Parameter predicate: The query predicate to perform.
/// - Returns: The `Object` found.
func fetchObject<T: Object>(_ predicate: (Query<T>) -> Query<Bool>) -> T? {
realm.objects(T.self).where(predicate).filter({ !$0.isInvalidated }).first
}
/// Fetch multiple `Object`s with a given query predicate.
/// - Parameter predicate: The query predicate to perform.
/// - Returns: The array `Object`s found.
func fetchObjects<T: Object>(_ predicate: (Query<T>) -> Query<Bool>) -> [T] {
realm.objects(T.self).where(predicate).filter({ !$0.isInvalidated })
}
/// Create a single `Object` if it doesn't exist in the Realm already, otherwise it updates it.
/// - Parameter object: The object to create or update, it must have a `primaryKey`.
func createOrUpdateObject<T: Object>(_ object: T) throws {
try realm.write {
realm.add(object, update: .modified)
}
}
/// Create multiple `Object`s if they don' exist in the Realm already, otherwise it updates them.
/// - Parameter objects: The objects to create or update, they all must have a `primaryKey`.
func createOrUpdateObjects<T: Object>(_ objects: [T]) throws {
try realm.write {
realm.add(objects, update: .modified)
}
}
/// Delete a single `Object` from the Realm with a given primaryKey.
/// - Parameters:
/// - primaryKey: The `Object` primary key.
func deleteObject<K: Hashable>(primaryKey: K) throws {
guard let objectToDelete = fetchObject(primaryKey: primaryKey) else { return }
try realm.write {
realm.delete(objectToDelete)
}
}
/// Delete multiple `Object`s of a certain `Type` from the Realm.
/// - Parameter type: The `Object` `Type` to delete.
func deleteObjects<T: Object>(_ type: T.Type) throws {
let objectsToDelete: [T] = fetchObjects()
guard !objectsToDelete.isEmpty else { return }
try realm.write {
realm.delete(objectsToDelete)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment