Search code examples
swiftxcodecore-data

What is the purpose for CoreData insert(object: NSManagedObject) function?


When do we have to use the function as we can easily save data without using it?


Solution

  • It's possible to create a managed object that's not inserted in a context, and insert it later. One use for this is if a user is creating a new entry, but hasn't tapped a "save" button yet. If they tap save, you insert the object. If they tap "cancel", you don't have to delete the object because it was never inserted in the first place.

    You could create an object like this with the NSManagedObject initializer init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?). The context argument is optional, so you could pass a nil value. Then later, if it makes sense, you could insert the new object into a context.