user1831622
user1831622

Reputation:

Realm + NSClassFromString

Hi everyone and thank you for be reading this.

I am new with Realm and I am stucked with a function that I can't figure out how to build. My intention is to have one function called func delete(className:String, id:Int){ that should be able to delete any object of any Realm class by its ID. The inner code of the function is:

func delete(objectNameV:String, id:Int){

   let theClass = NSClassFromString(objectNameV)

   // Get the default Realm
   let realm = try! Realm()
   let queryResult = realm.objects(theClass as! Object.Type).filter("id = \(id)")
   try! realm.write {
      realm.delete(queryResult)
   }
}

But the fact is that let theClass = NSClassFromString(objectNameV) it's allways NIL.

Any help is appreciated, i just need a function that given a realm classname and the id from an object of that class can delete it!

Realm version: 2.0.1 Xcode version: 8

Upvotes: 1

Views: 290

Answers (1)

TiM
TiM

Reputation: 15991

According to the Apple developer docs, classes in Swift are namespaced by their module names. So it's not sufficient to simply write the class name; you must also include their module name as well.

The example Apple used on their website is:

let myPersonClass: AnyClass? = NSClassFromString("MyGreatApp.Person")

Upvotes: 1

Related Questions