Search code examples
iosswiftrealm

how to make realm CRUD operation in separate swift file?


I am a beginner in iOS development and in programming, I am trying to make a swift file that contain realm CRUD operation called RealmService , so I don't have to write do catch block and try! realm all over the place, like my code below

import Foundation
import RealmSwift

class RealmService {

    var realm = try! Realm()

    func save(_ object: Object) {
        do {
            try realm.write {
                realm.add(object)
            }
        } catch {
            print("Failed to save \(object) in realm: \(error.localizedDescription)")
        }
    }

    func load(_ object: Object) -> Results<Object>? {
        return realm.objects(object.self)
    }

    func update(_ object: Object, with dictionary: [String: Any?]) {
        do {
            try realm.write {
                for (key, value) in dictionary {
                    object.setValue(value, forKey: key)
                }
            }
        } catch {
            print("Failed to update \(object) in realm: \(error.localizedDescription)")
        }
    }

    func delete(_ object: Object) {
        do {
            try realm.write {
                realm.delete(object)
            }
        } catch {
            print("Failed to delete \(object) in realm: \(error.localizedDescription)")
        }
    }
}

but in the load method, I get an error in the line realm.objects(object.self) , it is said

Cannot convert value of type 'Object' to expected argument type 'Object.Type'

enter image description here

I think I make mistake when insert object.self in the realm.objects. it should be element.type, but I dont have a clue what is this element type like this picture enter image description here

how to load data from realm? sadly i just know a little bit from youtube tutorial by using realm.objects(object.self)


Solution

  • You are doing the work of select through an object and this is a mistake because it is required of the type of object Element.Type and not the object itself

    try to use this

     func load<T: Object>(ofType: T.Type) -> Results<T> {
    
                return realm.objects(T.self)
    
        }
    

    call this func

    class MyObject: Object {
         ...
        @objc dynamic var name = ""
        ...
    
       }
      .....
      ream.objects(MyObject.self)