3 回答

TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個贊
(現(xiàn)在更新為Swift 3/4??梢栽诰庉嫐v史中找到早期Swift版本的解決方案。)
您可以使用unsafeDowncast
到的返回值轉(zhuǎn)換NSEntityDescription.insertNewObject()
到Self
(這是該方法實(shí)際上是所謂的類型):
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
。

TA貢獻(xiàn)1942條經(jīng)驗(yàn) 獲得超3個贊
這是通過實(shí)現(xiàn)初始化方法(使用Xcode 7.1測試)來解決問題的不同方法:
extension NSManagedObject { // Returns the unqualified class name, i.e. the last component. // Can be overridden in a subclass. class func entityName() -> String { return String(self) } convenience init(context: NSManagedObjectContext) { let eName = self.dynamicType.entityName() let entity = NSEntityDescription.entityForName(eName, inManagedObjectContext: context)! self.init(entity: entity, insertIntoManagedObjectContext: context) }}
Init方法具有隱式返回類型,Self
并且不需要強(qiáng)制轉(zhuǎn)換技巧。
let obj = YourEntity(context: context)
創(chuàng)建該YourEntity
類型的對象。
Swift 3/4更新:
extension NSManagedObject { // Returns the unqualified class name, i.e. the last component. // Can be overridden in a subclass. class func entityName() -> String { return String(describing: self) } convenience init(context: NSManagedObjectContext) { let eName = type(of: self).entityName() let entity = NSEntityDescription.entity(forEntityName: eName, in: context)! self.init(entity: entity, insertInto: context) }}

TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超8個贊
在Swift 2中,有一個使用協(xié)議和協(xié)議擴(kuò)展的非常智能的解決方案
protocol Fetchable{ typealias FetchableType: NSManagedObject static var entityName : String { get } static func createInContext(context: NSManagedObjectContext) -> FetchableType}extension Fetchable where Self : NSManagedObject, FetchableType == Self{ static func createInContext(context: NSManagedObjectContext) -> FetchableType { return NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: context) as! FetchableType }}
在每個NSManagedObject
子類中添加協(xié)議Fetchable
并實(shí)現(xiàn)該屬性entityName
。
現(xiàn)在該函數(shù)MyEntity.createInContext(…)
將返回正確的類型而無需進(jìn)一步的類型轉(zhuǎn)換。
- 3 回答
- 0 關(guān)注
- 564 瀏覽
添加回答
舉報(bào)