gpt4 book ai didi

Swift 在静态方法中初始化 Self

转载 作者:搜寻专家 更新时间:2023-11-01 07:22:50 26 4
gpt4 key购买 nike

在 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):

Constructing an object of class type Self with a metatype value must use a required initializer

最佳答案

为什么要为初始化器烦恼?

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 初始值设定项。

关于Swift 在静态方法中初始化 Self,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37768446/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com