Ios 在 Swift 2.2 中为 NSManagedObject 子类创建自定义初始化

Ios Create custom init for NSManagedObject subclass in Swift 2.2

A 使用 IOS9 和 Swift2.2

我想像创建一个 NSManagedObject 变量一样创建空的 init()

let NamTblVar = NamTblCls()
NamTblVar.Nam1Var = "TrlTxt1"
NamTblVar.Nam2Var = "TrlTxt2"
NamTblVar.Nam3Var = "TrlTxt2"
NamTblVar.SevDataFnc(NamTblVar)

并在自定义 NSManagedObject 中编写所有保存和检索函数 Class

我正在尝试创建自定义 class 但无法初始化 ()
出现错误:必须调用 superclass 'NSManagedObject'

的指定初始化程序

我试过了

class NamTblCls: NSManagedObject
{
    let ContxtVar = (UIApplication.sharedApplication().delegate as! AppDgtCls).managedObjectContext

    init()
    {
        super.init()

        super.init(entity: NSEntityDescription.entityForName("NamTbl", inManagedObjectContext: ContxtVar)!, insertIntoManagedObjectContext: ContxtVar)
    }

}

从技术上讲,这是您可以做到的方式:

let title = NSManagedObjectContextConcurrencyType(rawValue: 0)
let test: NSManagedObjectContext = NSManagedObjectContext(concurrencyType: title!)

class NamTblCls: NSManagedObject
{
    //let ContxtVar = (UIApplication.sharedApplication().delegate).managedObjectContext

    init(){
        super.init(entity: NSEntityDescription.entityForName("String", inManagedObjectContext: test)!, insertIntoManagedObjectContext: test)
    }
}

titletest 用于在操场上进行测试)

但实际上,您应该像这样设置 class

class NamTblCls: NSManagedObject
{
    //let ContxtVar = (UIApplication.sharedApplication().delegate).managedObjectContext

    init(entityName: String, someName: NSManagedObjectContextConcurrencyType){
        let test: NSManagedObjectContext = NSManagedObjectContext(concurrencyType: someName)
        super.init(entity: NSEntityDescription.entityForName(entityName, inManagedObjectContext: test)!, insertIntoManagedObjectContext: test)
    }
}

并在初始化 class 时创建 entityNameNSManagedObjectContextConcurrencyType