swiftinitializationnsmanagedobjectios9.3ios10.3

How to initialise a NSManagedObject subclass for iOS 10 and iOS 9.3 in Swift


I am writing an app in Swift 4 which should run for iOS 10.4 as well as for iOS 9.3. However, I have no idea how to implement the initialisers for both iOS versions.

I get the error message: CoreData: error: Failed to call designated initializer on NSManagedObject class 'DeltaSigmaTestsignalGenerator.Project'

The following empty subclass is created automatically by the Create NSManagedObject Subclass Generator:

import Foundation
import CoreData

public class Project: NSManagedObject {

}

The following function should generate a new Project Object

func addNewProject(projectName: String, version: String) {
    var newProject: Project!
    if #available(iOS 10.0, *) {
        newProject = Project(context: managedContext!)
    }
    else {
        newProject = Project()
    }

    newProject.projectName = projectName
    let newVersion = createNewVersion(versionName: version)
    newProject.addToVersions(newVersion)
    projekte.append(newProject)

    do {
        try managedContext!.save()
    }
    catch let error as NSError {
        print("Save error: \(error), \(error.userInfo)")
    }
}// End of addNewProject

Solution

  • In the else branch write

    newProject = NSEntityDescription.insertNewObject(forEntityName: "Project", into: managedContext!) as! Project
    

    and declare newProject as constant and non-optional (no, you won't get a compiler error)

    let newProject: Project