The most correct way of NSManagedObject initialization

34 Views Asked by At

I always create my maneged objects using this convenience init(context moc: NSManagedObjectContext).

However I came across this topic https://forums.developer.apple.com/forums/thread/74186

So, now I'm wondering which way is the most correct. I see at least 4 ways of NSManagedObject initialization now (excluding simple init()). Maybe some of them have performance advantages or something else? Could someone clarify it once and for all.

    // 1
    let managedObject = MyManagedObject(context: context)
    
    // 2
    let managedObject = NSManagedObject(
        entity: MyManagedObject.entity(),
        insertInto: context
    ) as? MyManagedObject
    
    // 3
    let entity = NSEntityDescription.entity(
        forEntityName: "MyManagedObject",
        in: context
    )
    let managedObject = NSManagedObject(
        entity: entity!,
        insertInto: context
    ) as? MyManagedObject
    
    // 4
    let managedObject = NSEntityDescription.insertNewObject(
        forEntityName: "MyManagedObject",
        into: context
    ) as? MyManagedObject
1

There are 1 best solutions below

0
vadian On BEST ANSWER

First of all the linked posting is 7 years old. The Swift language evolves pretty quickly.

Second of all the accepted answer is wrong. All your mentioned initialization methods do basically the same, they create an instance and insert it into the context.

However there are differences. Only way #1 returns a non-optional instance of the actual NSManagedObject subclass, MyManagedObject.

Way #2–#4 return an optional NSManagedObject instance – the base class – which must be cast to the desired type.

As far as I can remember the syntax of #1 has just been introduced at the time the topic was posted. Nowadays init(context:) is the highly recommended API because it's the safest one (no literal strings and no type cast involved) and it returns the proper type, thanks for having made many Core Data types generic.

And regarding performance there is no benefit of one over another.