Box

public class Box<E: EntityInspectable & __EntityRelatable>: CustomDebugStringConvertible
where E == E.EntityBindingType.EntityType

A box to store objects of a particular type.

Thread-safe.

  • The object type this box is managing.

    Declaration

    Swift

    public typealias EntityType = E
  • Indicates whether there are any objects stored inside the box.

    Declaration

    Swift

    public func isEmpty() throws -> Bool
  • Get an async box on which you can enqueue requests asynchronously.

    Declaration

    Swift

    private(set) public lazy var async: AsyncBox<E> { get set }
  • Returns the number of objects in this box, up to an optional maximum.

    Declaration

    Swift

    public func count(limit: Int = 0) throws -> Int

    Parameters

    limit

    Maximum value to count up to, or 0 for unlimited count.

    Return Value

    The count of all stored objects in this box or the given limit, whichever is lower.

  • Find out whether there is an object with the given ID in this box.

    Declaration

    Swift

    public func contains(_ entityId: EntityType.EntityBindingType.IdType) throws -> Bool

    Parameters

    entityId

    ID of the object.

    Return Value

    true if an object with this ID exists, false otherwise.

  • Find out whether objects with the given IDs exist in this box.

    Declaration

    Swift

    public func contains(_ ids: [EntityType.EntityBindingType.IdType]) throws -> Bool

    Parameters

    ids

    IDs of the objects.

    Return Value

    true if all objects specified exist.

  • Find out whether objects with the given IDs (passed individually, not as an array) exist in this box.

    Declaration

    Swift

    public func contains(_ ids: EntityType.EntityBindingType.IdType...) throws -> Bool

    Parameters

    ids

    IDs of the objects.

    Return Value

    true if all objects specified exist.

  • Puts the given struct in the box (aka persisting it). If the struct hadn’t been persisted yet, it will be assigned an ID, which will be written back to the entity’s ID property.

    Throws

    ObjectBoxError errors for database write errors.

    Declaration

    Swift

    @discardableResult
    public func put(_ entity: inout EntityType, mode: PutMode = .put) throws -> EntityType.EntityBindingType.IdType

    Parameters

    entity

    Object to persist.

    mode

    Whether you want to put (insert or update), insert (fail if there is an existing object of the given ID) or update (fail if the object doesn’t exist anymore).

    Return Value

    ID of the object after persistence. If entity was persisted before, it’s the same as its ID. If entity is a new object, this is the new ID that was generated.

  • Puts the given object in the box (aka persisting it). If the entity hadn’t been persisted yet, it will be assigned an ID, and if the entity is not a struct, the ID will be written back to the entity’s ID property. For a struct, either use the put(inout EntityType) variant or assign the returned ID to the ID property yourself.

    Throws

    ObjectBoxError errors for database write errors.

    Declaration

    Swift

    @discardableResult
    public func put(_ entity: EntityType, mode: PutMode = .put) throws -> EntityType.EntityBindingType.IdType

    Parameters

    entity

    Object to persist.

    mode

    Whether you want to put (insert or update), insert (fail if there is an existing object of the given ID) or update (fail if the object doesn’t exist anymore).

    Return Value

    ID of the object after persistence. If entity was persisted before, it’s the same as its ID. If entity is a new object, this is the new ID that was generated.

  • Puts the given entities in a box using a single transaction. Any entities that hadn’t been persisted yet will be assigned an ID. For classes, the entity’s ID property will be set to match any newly-assigned IDs. For structs, use the put(inout [EntityType]) variant or extract the IDs from the returned array of IDs and assign them to each entity.

    Throws

    ObjectBoxError errors for database write errors.

    Declaration

    Swift

    @discardableResult
    public func putAndReturnIDs <C: Collection>(_ entities: C, mode: PutMode = .put) throws
        -> [EntityType.EntityBindingType.IdType]
        where C.Element == EntityType

    Parameters

    entities

    Objects to persist.

    mode

    Whether you want to put (insert or update), insert (fail if there is an existing object of the given ID) or update (fail if the object doesn’t exist anymore).

    Return Value

    List of IDs of the entities were written to.

  • Puts the given entities in a box using a single transaction. Any entities that hadn’t been persisted yet will be assigned an ID. For classes, the entity’s ID property will be set to match any newly-assigned IDs. For structs, use the put(inout [EntityType]) variant or putAndReturnIDs() and assign the returned IDs to each entity.

    Throws

    ObjectBoxError errors for database write errors.

    Declaration

    Swift

    public func put<C: Collection>(_ entities: C, mode: PutMode = .put) throws
        where C.Element == EntityType

    Parameters

    entities

    Objects to persist.

  • Version of put([EntityType]) that is faster because it uses ContiguousArray.

    Declaration

    Swift

    public func put(_ entities: ContiguousArray<EntityType>, mode: PutMode = .put) throws
  • Puts the given structs in a box using a single transaction. Any entities that hadn’t been persisted yet will be assigned an ID. The entities’ ID properties will be set to match any newly-assigned IDs.

    Throws

    ObjectBoxError errors for database write errors.

    Declaration

    Swift

    public func put(_ entities: inout [EntityType], mode: PutMode = .put) throws

    Parameters

    entities

    Objects to persist and whose IDs will be updated if needed.

    mode

    Whether you want to put (insert or update), insert (fail if there is an existing object of the given ID) or update (fail if the object doesn’t exist anymore).

  • Puts the given entities in a box using a single transaction. Any entities that hadn’t been persisted yet will be assigned an ID. For classes, the entity’s ID property will be set to match any newly-assigned IDs. For structs, you will have to extract the IDs from the returned array of IDs and assign them to each entity.

    Throws

    ObjectBoxError errors for database write errors.

    Declaration

    Swift

    public func putAndReturnIDs(_ entities: EntityType..., mode: PutMode = .put) throws
        -> [EntityType.EntityBindingType.IdType]

    Parameters

    entities

    Objects to persist, passed as individual parameters, not as an array.

    Return Value

    List of IDs of the entities were written to.

  • Puts the given entities in a box using a single transaction. Any entities that hadn’t been persisted yet will be assigned an ID. For classes, the entity’s ID property will be set to match any newly-assigned IDs. For structs, use the put(inout [EntityType]) variant or putAndReturnIDs() and assign the returned IDs to each entity.

    Throws

    ObjectBoxError errors for database write errors.

    Declaration

    Swift

    public func put(_ entities: EntityType..., mode: PutMode = .put) throws

    Parameters

    entities

    Objects to persist, passed as individual parameters, not as an array.

  • Get the stored object for the given ID.

    Declaration

    Swift

    public func get<I>(_ entityId: I) throws -> EntityType? where I : UntypedIdBase

    Parameters

    entityId

    ID of the object.

    Return Value

    The entity, if an object with entityId was found, nil otherwise.

  • Get the stored object for the given ID.

    Declaration

    Swift

    public func get(_ id: EntityId<EntityType>) throws -> EntityType?

    Parameters

    entityId

    ID of the object.

    Return Value

    The entity, if an object with entityId was found, nil otherwise.

  • Gets the objects for the given IDs as an array.

    Declaration

    Swift

    public func get<I: IdBase, C: Collection>(_ ids: C, maxCount: Int = 0)
    throws -> [EntityType] where C.Element == I

    Parameters

    ids

    Object IDs to map to objects.

    Return Value

    An array of the objects that were actually found; in the order of the given IDs.

  • Gets the objects for the given IDs as a dictionary.

    Declaration

    Swift

    public func getAsDictionary<C: Collection>(_ ids: C) throws
        -> [EntityId<EntityType>: EntityType] where C.Element == EntityId<EntityType>

    Parameters

    ids

    Object IDs to map to objects.

    Return Value

    Dictionary of all ids and the corresponding objects. Nothing is added to the dictionary for entities that can’t be found.

  • Gets the objects for the given IDs as a dictionary.

    Declaration

    Swift

    public func getAsDictionary<I: UntypedIdBase, C: Collection>(_ ids: C) throws
        -> [I: EntityType] where C.Element == I

    Parameters

    ids

    Object IDs to map to objects.

    Return Value

    Dictionary of all ids and the corresponding objects. Nothing is added to the dictionary for entities that can’t be found.

  • Gets all objects from the box.

    Throws

    ObjectBoxError

    Declaration

    Swift

    public func all() throws -> [EntityType]

    Return Value

    All stored Objects in this Box.

  • Variant of all() that is faster due to using ContiguousArray.

    Declaration

    Swift

    public func allContiguous() throws -> ContiguousArray<EntityType>
  • Iterate over all objects in this box, calling the given closure with each object. This lazily creates one object after the other and hands them to you, and if you do not hold on to the objects, will free their memory once done.

    Declaration

    Swift

    public func visit(writable: Bool = false, visitor: (EntityType) throws -> Bool) throws

    Parameters

    visitor

    A closure that is called for each object in this box. Return true to keep going, false to abort the loop. Exceptions thrown by the closure are re-thrown.

  • Iterate over all objects in this box, calling the given closure with each object. This lazily creates one object after the other and hands them to you, and if you do not hold on to the objects, will free their memory once done.

    Declaration

    Swift

    public func forEach(writable: Bool = false, _ visitor: (EntityType) throws -> Void) throws

    Parameters

    writable

    By default the objects are traversed for read-only access. If you want to write, enable this flag to makes the enclosing transaction writable.

    visitor

    A closure that is called for each object in this box. Exceptions thrown by the closure are re-thrown.

  • Iterate over the objects in this box with the given IDs, calling the given closure with each object. This lazily creates one object after the other and hands them to you, and if you do not hold on to the objects, will free their memory once done.

    Declaration

    Swift

    public func `for`<C: Collection>(writable: Bool = false, _ ids: C, in visitor: (EntityType?) throws -> Void) throws
        where C.Element == EntityType.EntityBindingType.IdType

    Parameters

    writable

    By default the objects are traversed for read-only access. If you want to write, enable this flag to makes the enclosing transaction writable.

    visitor

    A closure that is called for each object requested. If an object with the requested ID can’t be found, you get a callback with a NIL entity. Exceptions thrown by the closure are re-thrown.

  • Iterate over the objects in this box with the given IDs, calling the given closure with each object. This lazily creates one object after the other and hands them to you, and if you do not hold on to the objects, will free their memory once done.

    Declaration

    Swift

    public func visit<C: Collection>(writable: Bool = false, _ ids: C, in visitor: (EntityType?) throws -> Bool) throws
    where C.Element == EntityType.EntityBindingType.IdType

    Parameters

    writable

    By default the objects are traversed for read-only access. If you want to write, enable this flag to makes the enclosing transaction writable.

    visitor

    A closure that is called for each object requested. If an object with the requested ID can’t be found, you get a callback with a NIL entity. Exceptions thrown by the closure are re-thrown.

  • Removes (deletes) the Object by its ID.

    Throws

    ObjectBoxError errors for database write errors, .notFound if there is no object of that ID.

    Declaration

    Swift

    @discardableResult
    public func remove<I>(_ entityId: I) throws -> Bool where I : UntypedIdBase

    Parameters

    entityId

    ID of the object to delete.

    Return Value

    false if entityId is 0, true if the object was successfully deleted.

  • Removes (deletes) the Object by its ID.

    Throws

    ObjectBoxError errors for database write errors, .notFound if there is no object of that ID.

    Declaration

    Swift

    @discardableResult
    public func remove(_ entityId: EntityId<EntityType>) throws -> Bool

    Parameters

    entityId

    ID of the object to delete.

    Return Value

    false if entityId is 0, true if the object was successfully deleted.

  • Removes (deletes) the given Object.

    Throws

    ObjectBoxError errors for database write errors, .notFound if there is no object of that ID anymore.

    Declaration

    Swift

    @discardableResult
    public func remove(_ entity: EntityType) throws -> Bool

    Parameters

    entity

    Object to delete.

    Return Value

    false if the object was never persisted, true if the object was successfully deleted.

  • Removes (deletes) the given objects in a single transaction.

    It is valid to pass objects here that haven’t been persisted yet.

    Throws

    ObjectBoxError errors for database write errors. Will not throw if an object can’t be found in the database. Use contains() or check the returned number of deleted entities if you need to fail.

    Declaration

    Swift

    @discardableResult
    public func remove<C: Collection>(_ entities: C) throws -> UInt64
        where C.Element == EntityType

    Parameters

    entities

    Objects to delete.

    Return Value

    Count of objects that were removed.

  • Version of remove() that is faster because it uses ContiguousArray.

    Declaration

    Swift

    @discardableResult
    public func remove(_ entities: ContiguousArray<EntityType>) throws -> UInt64
  • Removes (deletes) the given objects (passed as individual parameters) in a single transaction.

    It is valid to pass objects here that haven’t been persisted yet.

    Throws

    ObjectBoxError errors for database write errors. Will not throw if an object can’t be found in the database. Use contains() or check the returned number of deleted entities if you need to fail.

    Declaration

    Swift

    @discardableResult
    public func remove(_ entities: EntityType...) throws -> UInt64

    Parameters

    entities

    Objects to delete.

    Return Value

    Count of objects that were removed.

  • Removes (deletes) the objects with the given IDs in a single transaction.

    It is valid to pass IDs of objects here that haven’t been persisted yet (i.e. any 0 ID is skipped). If an entity is passed whose ID doesn’t exist anymore, only the entities up to that entity will be removed.

    Throws

    ObjectBoxError errors for database write errors. Will not throw if an object can’t be found in the database. Use contains() or check the returned number of deleted entities if you need to fail.

    Declaration

    Swift

    @discardableResult
    public func remove<I: UntypedIdBase, C: Collection>(_ ids: C) throws -> UInt64
        where C.Element == I

    Parameters

    ids

    IDs of objects to delete.

    Return Value

    Count of objects that were removed.

  • Removes (deletes) the objects with the given IDs (passed as individual parameters) in a single transaction.

    It is valid to pass IDs of objects here that haven’t been persisted yet (i.e. any 0 ID is skipped). If an entity is passed whose ID doesn’t exist anymore, only the entities up to that entity will be removed.

    Throws

    ObjectBoxError errors for database write errors. Will not throw if an object can’t be found in the database. Use contains() or check the returned number of deleted entities if you need to fail.

    Declaration

    Swift

    @discardableResult
    public func remove<I>(_ ids: I...) throws -> UInt64 where I : UntypedIdBase

    Parameters

    entities

    Objects to delete.

    Return Value

    Count of objects that were removed.

  • Removes (deletes) the objects with the given IDs in a single transaction.

    It is valid to pass IDs of objects here that haven’t been persisted yet (i.e. any 0 ID is skipped). If an entity is passed whose ID doesn’t exist anymore, only the entities up to that entity will be removed.

    Throws

    ObjectBoxError errors for database write errors. Will not throw if an object can’t be found in the database. Use contains() or check the returned number of deleted entities if you need to fail.

    Declaration

    Swift

    @discardableResult
    public func remove<C: Collection>(_ entityIDs: C) throws -> UInt64
        where C.Element == EntityId<EntityType>

    Parameters

    ids

    IDs of objects to delete.

    Return Value

    Count of objects that were removed.

  • Removes (deletes) the objects with the given IDs (passed as individual objects) in a single transaction.

    It is valid to pass IDs of objects here that haven’t been persisted yet (i.e. any 0 ID is skipped). If an entity is passed whose ID doesn’t exist anymore, only the entities up to that entity will be removed.

    Throws

    ObjectBoxError errors for database write errors. Will not throw if an object can’t be found in the database. Use contains() or check the returned number of deleted entities if you need to fail.

    Declaration

    Swift

    @discardableResult
    public func remove(_ ids: EntityId<EntityType>...) throws -> UInt64

    Parameters

    entities

    Objects to delete.

    Return Value

    Count of objects that were removed.

  • Removes (deletes) all objects in a single transaction.

    Throws

    ObjectBoxError errors for database write errors.

    Declaration

    Swift

    @discardableResult
    public func removeAll() throws -> UInt64

    Return Value

    Count of items that were removed.

  • Return a Combine publisher for this box that you can subscribe to, to be notified of changes in this box.

    Declaration

    Swift

    public var publisher: BoxPublisher<EntityType> { get }
  • Receive a callback whenever an entity in this box is added/removed or modified. This variant does not pass the objects in the box to your callback for the case where you just want to display their count or are even interested only in whether there are objects or not.

    See also

    Box.subscribe(dispatchQueue:,resultHandler:)

    Declaration

    Swift

    public func subscribe(dispatchQueue: DispatchQueue = DispatchQueue.main,
                          flags: Observer.Flags = [.sendInitial],
                          changeHandler: @escaping () -> Void) -> Observer

    Parameters

    dispatchQueue

    The dispatch queue on which you want your callback to be called.

    flags

    Flags to control behavior of the subscription

    changeHandler

    A closure to be called when a change occurs.

    Return Value

    An object representing your observer connection. As long as this object exists, your callback will be called. If you no longer want to receive callbacks, let go of your reference to this object so it is deinited.

  • Receive a callback whenever an entity in this box is added/removed or modified. The callback receives the current list of entities in this box as a parameter, allowing you to e.g. feed it to Combine or an Rx subscriber.

    See also

    Box.subscribe(dispatchQueue:,changeHandler:)

    Declaration

    Swift

    public func subscribe(dispatchQueue: DispatchQueue = DispatchQueue.main,
                          flags: Observer.Flags = [.sendInitial],
                          resultHandler: @escaping ([EntityType], ObjectBoxError?) -> Void) -> Observer

    Parameters

    dispatchQueue

    The dispatch queue on which you want your callback to be called.

    flags

    Flags to control behavior of the subscription

    resultHandler

    A closure that will be passed an array of the objects in this box whenever the box contents change.

    Return Value

    An object representing your observer connection. As long as the Observer object exists, your callback will be called. If you no longer want to receive callbacks, let go of your reference to this object so it is deinited.

  • Variant of subscribe() that is faster due to using ContiguousArray.

    Declaration

    Swift

    public func subscribeContiguous(dispatchQueue: DispatchQueue = DispatchQueue.main,
                                    flags: Observer.Flags = [.sendInitial],
                                    resultHandler:
        @escaping (ContiguousArray<EntityType>, ObjectBoxError?) -> Void) -> Observer
  • Create a blank QueryBuilder you can configure afterwards. This is useful if you don’t want to filter but still want to perform a link (join) or control the order of results.

    Call build() on the QueryBuilder to obtain a Query that you can actually run or whose placeholder values you can modify.

    Declaration

    Swift

    public func query() -> QueryBuilder<EntityType>

    Return Value

    QueryBuilder for a blank query.

  • Return a QueryBuilder that can be used to create a Query with conditions expressed inside a block.

    Example:

    let personBox: Box<Person> = store.box()
    let query = personBox.query { Person.name.startsWith("M") && Person.age >= 18 }.build()
    

    The list of supported operators and methods for each property depends on its type. Number-based properties offer methods like isBetween, while String-based properties offer startsWith, contains etc.

    You can explore Xcode’s auto-completion or refer to our documentation at https://swift.objectbox.io.

    Call build() on the QueryBuilder to obtain a Query that you can actually run or whose placeholder values you can modify.

    Declaration

    Swift

    public func query(_ conditions: () -> QueryCondition<EntityType>) -> QueryBuilder<EntityType>