
(现在为Swift 3/4更新。可以在编辑历史记录中找到早期Swift版本的解决方案。)
您可以使用
unsafeDowncast到的返回值转换
NSEntityDescription.insertNewObject()到
Self
(这是该方法实际上是所谓的类型):
extension NSManagedObject { class func create(in context: NSManagedObjectContext) -> Self { let classname = entityName() let object = NSEntityDescription.insertNewObject(forEntityName: classname, into: context) return unsafeDowncast(object, to: self) } // Returns the unqualified class name, i.e. the last component. // Can be overridden in a subclass. class func entityName() -> String { return String(describing: self) }}然后
let obj = YourEntity.createInContext(context)
工作,并且编译器将
obj正确的类型推断为
YourEntity。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)