Swift在静态方法中初始化Self

时间:2016-06-11 20:57:15

标签: swift

让问题变得有效,在User.provideInstance中我无法初始化Self并返回。有什么想法吗?

extension NSManagedObject {
    public convenience init(managedObjectContext: NSManagedObjectContext) {
        let entity = NSEntityDescription.entityForName(String(self.dynamicType), inManagedObjectContext: managedObjectContext)!
        self.init(entity: entity, insertIntoManagedObjectContext: managedObjectContext)
    }
}

public protocol Deserializable {
    static func provideInstance(json: [NSObject: AnyObject]) -> Self
}

@objc(User) public class User: NSManagedObject, Deserializable {

    public static func provideInstance(json: [NSObject: AnyObject]) -> Self {
       let context = DIContainer.instance.resolve(CoreDataStack.self).managedObjectContext
       let instance = self.init(managedObjectContext: context)
       return instance
    }
}

错误发生在let instance = self.init(managedObjectContext: context)

  

构造具有元类型值的类类型Self的对象必须使用必需的初始值设定项

2 个答案:

答案 0 :(得分:1)

正如错误所说,你需要一个必需的初始化器来创建一个对象,这就是你的子类。在课前添加final以防止此错误。

如果你需要子类,请尝试这个:

@objc(User) public class User: NSManagedObject, Deserializable {

private static func pInstance<T>(json: [NSObject: AnyObject]) -> T {
    let context = DIContainer.instance.resolve(CoreDataStack.self).managedObjectContext
    let copy: NSManagedObject = NSManagedObject(managedObjectContext: context)
    let instance = copy as! T
    return instance
}

public static func provideInstance(json: [NSObject: AnyObject]) -> Self {
        return pInstance(json)
    }
}

基本上,创建一个辅助函数来基于基类NSManagedObject创建T的实例。然后使用实际的provideInstance函数和推断类型Self。

答案 1 :(得分:1)

为什么要使用初始化程序?

'use strict';
const EventEmitter = require('events');

class Downloader extends EventEmitter{
    download(delaySecs){
        setTimeout(() => {
            if(this.totalEmitted == undefined) this.totalEmitted = 0;
            this.totalEmitted ++;
            this.emit('downloaded',delaySecs,this.totalEmitted);            
        },delaySecs*1000)
    }
}

module.exports = Downloader;

初始值设定项的问题在于它们并不总是被继承,除非它们是extension NSManagedObject { class func provide(managedObjectContext managedObjectContext: NSManagedObjectContext) -> Self { let entity = NSEntityDescription.entityForName(String(self.dynamicType), inManagedObjectContext: managedObjectContext)! return self.init(entity: entity, insertIntoManagedObjectContext: managedObjectContext) } } public protocol Deserializable { static func provideInstance(json: [NSObject: AnyObject]) -> Self } @objc(User) public class User: NSManagedObject, Deserializable { public static func provideInstance(json: [NSObject: AnyObject]) -> Self { let context = ... let instance = self.provide(managedObjectContext: context) return instance } } 。而且您无法在扩展程序中创建required初始值设定项。