[英]swift mirror return class name in class function
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. 唯一的问题是,例如,一个汽车类扩展了这个AbstractEntity,并调用了该方法打印出Car.Type,这是正确的,但是我不希望扩展名为.Type。 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..
我知道NSObject的出现,然后是NSStringFromClass的事情。
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. 那是我的AbstractEntity,模型中的每个实体都对此进行了扩展。 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. 例如,现在我有一个Car实体,我想做Car.find ...,它返回了我一辆Car。 That why I (think) I need the class name so that I can use it to fetch it with the NSFetchRequest(entityName: entityName).
这就是为什么我(想)我需要类名,以便可以使用它通过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.
我现在传入我想获取的entityName,但是我认为这很丑陋,因为当您执行Car.find ..时,您知道您想要一辆汽车。
Really i don't get your question, but according to my requirement you need following functionality. 确实我没有收到您的问题,但是根据我的要求,您需要以下功能。
class AbstractEntity {
class func findOrCreateEntity() {
let str = __FILE__
let fullNameArr = str.componentsSeparatedByString("/")
print("Name: \(fullNameArr.last!)")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.