简体   繁体   中英

How to make generic function to delete data in two Realm tables?

Code:

  class Realm_manager {

        private init() {}

        static let shared = Realm_manager()

        let realm = try! Realm()

         func deleteObjects<T: Object,T2: Object>(id: String,obj1: T,obj2: T2) {
             try! realm.write {
            realm.delete(realm.objects(T2.self).filter("set_id=%@", id))
            realm.delete(realm.objects(T.self).filter("id=%@", id))
        }
    }
    }

function call in VC:

Realm_manager.shared.deleteObjects(id: array[indexPath.row].id, obj1: className1, obj2: className2)

Error in VC:

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


How can I solve this error?

How you're getting/setting className1 and className2? Should work like:

let object = Object()
deleteObjects(id: "1234", obj1: object, obj2: object)

Actually, your deleteObjects don't need to know anything about real objects. Could:

func deleteObjects<T: Object,T2: Object>(id: String, obj1: T.Type, obj2: T2.Type) {
    try! realm.write {
        realm.delete(realm.objects(T2.self).filter("set_id=%@", id))
        realm.delete(realm.objects(T.self).filter("id=%@", id))
    }
}

And call:

deleteObjects(id: "1234", obj1: Object.self, obj2: Object.self)

Or more convinient would be:

func deleteObjectsWith(id: String, withTypes types: [Object.Type]) {
    try! realm.write {
        types.forEach { objectType in
            let objects = realm.objects(objectType).filter("set_id=%@", id)
            realm.delete(objects)
        }
    }
}

And call:

deleteObjectsWith(id: "1234", withTypes: [Object.self, Object.self])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM