NSManagedObjectContext

extension NSManagedObjectContext

Useful extensions to NSManagedObjectContext

  • Create a new managed object of type A and insert it into the managed context.

    Declaration

    Swift

    @discardableResult
    public func insertObject<A>(_ config: ((A) -> A) = { $0 }) -> A
    where A: Managed

    Return Value

    new managed object of type A

  • Save changes made to entities managed by this context

    Declaration

    Swift

    public func saveChanges() throws
  • Save changes made to entities managed by this context without blocking.

    Declaration

    Swift

    public func saveChangesAsync()
  • Attempt to save the context to storage, rolling back if the save fails.

    Declaration

    Swift

    @discardableResult
    public func saveOrRollback() -> Bool

    Return Value

    true if saved

  • Execute a block asynchronously and then try to save the context.

    Declaration

    Swift

    public func performChangesAndSaveAsync(block: @escaping () -> Void)

    Parameters

    block

    block to execute

  • Register to receive notifications when this context has been saved.

    Declaration

    Swift

    public func notifyOnSave<T: NSManagedObject>(_ block: @escaping (ContextNotification<T>) -> Void)
      -> NSObjectProtocol

    Parameters

    block

    the block to execute after a save. It will receive a ContextNotification that identifies the objects that were added, updated, and/or deleted since the last save event.

    Return Value

    reference to the observation

  • Register to receive notifications when this context is processing changes but before they have been saved.

    Declaration

    Swift

    public func notifyOnChanges<T: NSManagedObject>(
      _ block: @escaping (ContextNotification<T>) -> Void
    ) -> NSObjectProtocol

    Parameters

    block

    the block to execute after a save. It will receive a ContextNotification that identifies the objects that were added, updated, and/or deleted since the last save event.

    Return Value

    reference to the observation

  • Set a managed object in a cache.

    Declaration

    Swift

    public func set(_ object: NSManagedObject?, forSingleObjectCacheKey key: String)

    Parameters

    object

    the value to cache

    key

    the key to store under

  • Obtain an object from the cache

    Declaration

    Swift

    public func object<T>(forSingleObjectCacheKey key: String) -> T? where T : NSManagedObject

    Parameters

    key

    the value to look for

    Return Value

    object found in cache or nil