I'm having a class function and in that class function I want the name of the class thats extending this abstract entity class.
I found the Mirror type could do this so I have something like this:
class AbstractEntity {
class func findOrCreateEntity() -> AnyObject? {
print("Name: \(NSStringFromClass(Mirror(reflecting: self)))")
}
}
The only problem is that for example a class Car extends this AbstractEntity and it calls the method this prints Car.Type, this is correct but I don't want the .Type extension. Is there any way to just get the class name?
I really want to do it the swift way if it's possible. I know of the exnteions of NSObject and then the NSStringFromClass thing..
For clarity:
class AbstractEntity: NSManagedObject {
// Insert code here to add functionality to your managed object subclass
class func findOrCreateEntityWithUUID(entityName: String, uuid: String, context: NSManagedObjectContext) -> AnyObject? {
let request = NSFetchRequest(entityName: entityName)
request.returnsObjectsAsFaults = false;
let predicate = NSPredicate(format: "uuid = %@", uuid)
request.predicate = predicate
do {
var results = try context.executeFetchRequest(request)
if results.count > 0 {
return results[0]
} else {
let entity = NSEntityDescription.entityForName(entityName, inManagedObjectContext: context)
let abstractEntity = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: context)
abstractEntity.setValue(uuid, forKey: "uuid")
return abstractEntity
}
} catch let error as NSError {
DDLogError("Fetch failed: \(error.localizedDescription)")
}
return nil
}
}
That's my AbstractEntity and every entity in my model extends that. So I have one place where I want my logic.
Now for example I have a Car entity and I want to do Car.find... and it returns me a Car. That why I (think) I need the class name so that I can use it to fetch it with the NSFetchRequest(entityName: entityName). I now pass in the entityName I want to fetch but I think this is ugly because when you do Car.find.. you know you want a car.