2015-09-05 57 views
2

我通常会将create...:inContext:方法添加到我的NSManagedObject子类中,这些子类插入并初始化该对象。因此,举例来说:你能得到调用超级方法的子类的名字吗?

class Example : NSManagedObject { 
    class func createWithArgument(arg: Int, inContext context: NSManagedObjectContext) -> Example { 
     let example = NSEntityDescription.insertNewObjectForEntityForName("Example", inManagedObjectContext: context) as! Example 

     // ... 
    } 
} 

也能正常工作的具体类别,但如果Example是一个抽象模型,然后硬编码"Example"将无法​​正常工作。我希望能够做的是插入其调用createWithArgument:inContext:方法的实体的类型,所以我可以做这样的事情:

class SpecificExample : Example { 
    class func createInContext(context: NSManagedObjectContext) -> SpecificExample { 
     return super.createWithArgument(2, inContext: context) // always 2 because reasons 
    } 
} 

我最初的计划是只抓调用的名称键入并使用它作为实体名称(前提是类和实体名称始终匹配)。

不幸的是,这似乎并不奏效;正如你所看到的,你总能得到家长的类型,即使你调用该方法在子类:

import UIKit 

class Parent { 
    class func getClassName(type: Any? = nil) -> String { 
     return _stdlib_getDemangledTypeName(type ?? self).componentsSeparatedByString(".").first! 
    } 
} 

class FirstChild : Parent { 

} 

class SecondChild : Parent { 
    override class func getClassName(type: Any? = nil) -> String { 
     return super.getClassName(self) 
    } 
} 


Parent.getClassName() // Parent 
FirstChild.getClassName() // Parent 
SecondChild.getClassName() // SecondChild 

现在,在我的具体的例子,还有其他的方法来达到同样的结果(例如,创建对象,然后调用继承的init方法)。

但是,我现在好奇这种反思在Swift中是否可能。有没有一种方法来实现这一目标?

+0

在面向对象编程中,只要你认为你需要知道类的_name_,你应该再想一想。整个概念是一种“难闻的气味”。 – matt

+0

@matt绝对同意,但CoreData需要知道实体的名称(作为字符串)才能将其插入到数据库中,所以这是一种特殊情况。 – sapi

回答

1

我不太明白为什么你不使用NSStringFromClass()

class Parent { 
    class func whoami() -> String { 
     return NSStringFromClass(self) 
    } 
} 
class FirstChild : Parent { 
} 
class SecondChild : Parent { 
} 

而且还有一个纯斯威夫特相当于(或toString()雨燕1.2及以前)String()

class Parent { 
    class func whoami() -> String { 
     return String(self) 
    } 
} 
class FirstChild : Parent { 
} 
class SecondChild : Parent { 
} 
+0

谢谢,这是有效的。任何想法为什么'NSStringFromClass'工作在'_stdlib_getDemangledTypeName'不? – sapi