Search code examples
iosswiftcore-datansmanagedobjectnsmanagedobjectcontext

CoreData extension: insert NSManagedObject in NSManagedObjectContext


Usually, when I need to insert a new object into the CoreData's NSManagedObjectContext, I have to do it in the following manner:


        let device = NSEntityDescription.insertNewObject(forEntityName: "Device", into: context) as! Device
        device. .....// call methods on "device"

However, it makes the process error-prone since the return type of the .insertNewObject(forEntityName: is not type-safe and requires a forced cast. Also, the entityName parameter won't be fetched if the class will be refactored, making it a potential source of runtime errors which are really hard to trace.

I'm interested in using a more type-safe approach that would minimize the risk of programmer's error, e.g. by introducing the following extension for the whole Swift module:

import CoreData

extension NSManagedObject {
    class func insert(in context: NSManagedObjectContext) -> Self {
        return NSEntityDescription.insertNewObject(forEntityName: String(describing: self), into: context) as! Self
    }
}

After introducing this extension, the code at the call site looks as follows:

        let device = Device.insert(in: context)
        device. .....// call methods on "device"

If the Device class is renamed, the method parameter entityName will be also changed accordingly.

Are there any potential limitations of this approach?


Solution

  • Why not use

    let device = Device(context: context)
    

    Which was added in iOS10 for this exact reason?