2

Let's say I have a CoreData entity called Person:

class Person: NSManagedObject {
    // ...
}

I have been trying to implement a static function create as an extension of NSManagedObject.

extension NSManagedObject {
    static func create() -> ??? {
        let object = ???
        CRUD.insertToDatabase(object) // Insert object to database
        return object
    }
}

Here I want create() to return an instance of the type from which NSManagedObject is inherited. For example, when I call create() from Person I want it to return a Person instance. When I call it from the Animal class it has to return an instance of type Animal.

let person = Person.create() // -> Returns a Person instance
let animal = Animal.create() // -> Returns an Animal instance

I'd appreciate any help on how to implement this kind of function in the parent class.

Jake A.
  • 540
  • 5
  • 12

1 Answers1

1

It is not clear what your CRUD call is supposed to do since when you instantiate a NSManagedObject subclass it is automatically inserted into the context but a static method could looks like this, note that you need to send the NSManagedObjectContext since this is a static method

static func create<T: NSManagedObject>(in context: NSManagedObjectContext) -> T {
    let object = T(context: context)
    CRUD.insertToDatabase(object) //what happens here? Why send object?
    return object
}

an alternative is to let the CRUD do this directly

func insertToDatabase<T: NSManagedObject>() -> T {
    let object = T(context: self.mainContext)
    //save?
    return object
}

the first would then be called like this

let person = Person.create(in: someContext)

and the second

let person: Person = CRUD.insertToDatabase()
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52