gpt4 book ai didi

ios - 如何在 Swift 中为 NSManagedObject 子类指定初始化器?

转载 作者:IT王子 更新时间:2023-10-29 05:04:26 26 4
gpt4 key购买 nike

class Alternative: NSManagedObject {

@NSManaged var text: String
@NSManaged var isCorrect: Bool
@NSManaged var image: NSData
}

convenience init(text: String, isCorrect: Bool, entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext!) {
let alternative = Alternative(entity: entity, insertIntoManagedObjectContext: context) as Alternative
alternative.text = text
alternative.isCorrect = isCorrect
return alternative
}

我想创建一个方法,让我可以通过这个调用来初始化新对象:

let newAlternative = Alternative("third platform", True, entityDescription, managedObjectContext)

但是我得到了错误:

Convenience initializer for Alternative must delegate with self.init

我需要在我的初始化程序中更改什么才能使我的示例用法正常工作?

最佳答案

便捷初始化器必须在self 上调用指定的初始化器:

convenience init(text: String, isCorrect: Bool, entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext!) {
self.init(entity: entity, insertIntoManagedObjectContext: context)
self.text = text
self.isCorrect = isCorrect
}

这将被称为

let newAlternative = Alternative(text: "third platform", isCorrect: true,
entity: entityDescription, insertIntoManagedObjectContext: managedObjectContext)

此外,您还可以将实体描述的创建移动到便利初始值设定项中,而不是将其作为参数传递(由Mundi 的回答):

convenience init(text: String, isCorrect: Bool, insertIntoManagedObjectContext context: NSManagedObjectContext!) {
let entity = NSEntityDescription.entityForName("Alternative", inManagedObjectContext: context)!
self.init(entity: entity, insertIntoManagedObjectContext: context)
self.text = text
self.isCorrect = isCorrect
}

关于ios - 如何在 Swift 中为 NSManagedObject 子类指定初始化器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26428366/

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