Sujay U N
Sujay U N

Reputation: 5340

Ios Create custom init for NSManagedObject subclass in Swift 2.2

A using IOS9 and Swift2.2

I want to create empty init() as creating a NSManagedObject Variable like

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

And write all the save and retrieve functions in custom NSManagedObject Class

I am trying to create custom class but not able to init()
Getting a error: Must call a designated initialiser of the superclass 'NSManagedObject'

I Tried

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

    init()
    {
        super.init()

and

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

}

Upvotes: 1

Views: 1541

Answers (1)

Caleb Kleveter
Caleb Kleveter

Reputation: 11494

Technically, this is a way you might be able to do it:

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)
    }
}

(title and test are for testing in the playground)

But in reality, you should probably setup your class like this:

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)
    }
}

And create the entityName and NSManagedObjectContextConcurrencyType when you initialize the class.

Upvotes: 2

Related Questions