Getting Started Using ObjectBox in Your Project

Learn how to use the ObjectBox Framework to persist and read objects.

To see ObjectBox in action, you need to

  1. Install ObjectBox if you haven't already.

  2. Define your Entities, i.e. the classes you want to persist;

  3. import ObjectBox into your source file

Define your Entities

ObjectBox uses code generation to read and write your objects instead of forcing you to inherit from a base object. To mark an object as an entity, you have two options:

  1. Simply conform to the Entity protocol, or

  2. add // objectbox:Entity before the type as an annotation for the code generator.

Then supply an ID property and parameter-less initializer init(), and you're good to go:

import ObjectBox
class ExampleEntity: Entity {
var id: Id<ExampleEntity> = 0
required init() {
// nothing to do here, ObjectBox calls this
}
}

That is all you need to get going. Build your project and ObjectBox's code generator will generate the boilerplate code to persist and read objects of this type.

You initialize an Id with 0 for all entities. This tells ObjectBox your object isn't persisted, yet. When you persist objects, the ID will be changed to the actual value. And once an entity has a non-zero ID, persisting changes will update the existing record instead of creating a new one.

So the ID is managed by ObjectBox. Conversely, you do not want to modify it yourself.

Ways to Define IDs

To specify Entity IDs, you need to have a property of type Id<EntityName> , where "EntityName" is the name of your class, of course. The code generator will look for one of these configurations, in the following order

  1. A property that has a // objectbox: entityId comment annotation on the line above the property definition.

  2. A property named var id: Id<EntityName>.

  3. Any other property of the Id<EntityName> type, if there is only one.

You usually don't need more than one property of the Id<EntityName> type, use ObjectBox's support for object relations if you need to connect entities with each other. In any case, should you need to store a reference to another object for an unusual purpose, simply use annotations to ensure ObjectBox uses the right property as the entity's ID.

Here's an example of using annotations in action:

// objectbox: Entity
class ExampleEntity {
var anotherID: Id<ExampleEntity> = 0
// objectbox: entityId
var theEntityIdentifier: Id<ExampleEntity> = 0 // <- this will be used
required init() {
// nothing to do here
}
}

Initialize a Store

To create or access a database on disk, use the ObjectBox.Store class. The Store behaves much like a database connection: you keep the instance around to maintain an open connection to the data on disk. usually for the lifetime of your app.

let store = Store(directoryPath: "/path/to/the/store")

When you use the store constructor that's been generated for you, it will register your entities for you. Should you use one of the other constructors, you will have to register your entities yourself at application startup. This will make the structure of your entities known to the store, similar to registering a database schema iteratively.

store.registerAllEntities()

Working with Object Boxes

Since ObjectBox is all about sticking objects in boxes, you interact with objects using aBoxinterface. For each object class, there is a matching Box instance.

To manage your entities, you retrieve the ObjectBox.Box<T> instance for its class from yourStore. Boxes are lightweight and can be discarded, but then you have to pass the Store around. You will almost always prefer to pass long-lived Box instances around instead, for example in segues between UIViewControllers.

let exampleEntityBox: Box<ExampleEntity> = store.box(for: ExampleEntity.self)
// Similarly:
let personBox: Box<Person> = store.box(for: Person.self)
let noteBox: Box<Note> = store.box(for: Note.self)

Wherever you have access to a Box, you can use it to persist objects and fetch objects from disk. Boxes are thread safe. Here are some of the basic operations:

  • put: Persist an object, which may overwrite an existing object with the same ID. In other words, use putto insert or update objects. When put succeeds, an ID will be assigned to the entity. There are put variants that support writing multiple objects at once, which is more efficient than writing each with its own call to put.

  • get: When you have an object's ID, you can get to the object very efficiently using get. To get all objects of a type, use all.

  • remove: Deletes a previously persisted object from its box. There are method overloads to remove multiple entities, and removeAll to delete all objects and empty the box.

  • count: The number of objects stored in this box.

  • query: Lets you provide a query expression to retrieve objects by certain criteria. See the page on queries for details.

Check the API docs for Box for a list of operations.

Put and Get Example

Once you have a box, it is simple to persist an entity. To illustrate the change of IDs, we added assertions to the code; you don't need these, of course.

// let's start with an empty box
assert(exampleEntityBox.all().isEmpty)
let exampleEntity = ExampleEntity()
assert(exampleEntity.id.value == 0)
let newID = exampleEntityBox.put(exampleEntity)
// Change of ID with the `put`:
assert(exampleEntity.id.value != 0)
assert(exampleEntity.id == newID)
// Check the Box contents did indeed change:
assert(exampleEntityBox.count == 1)
assert(exampleEntityBox.all().first?.id == newID)
// Getting to a specific object
guard let foundEntity = exampleEntityBox.get(newID)
else { fatalError("Object should be in the box") }
assert(exampleEntity.id == foundEntity.id)
// Cleaning up
exampleEntityBox.removeAll()
assert(exampleEntityBox.count == 0)

Transactions

Transactions in ObjectBox let you group together several operations and ensure that either all of them complete, or none does, always leaving your data relations in a consistent state. If you do not run your own transaction, ObjectBox will implicitly create one for every call:

  • A put runs an implicit transaction.

  • Prefer the put variant that takes an array of entities (like put([person1, person2])) whenever possible to increase performance.

For a high number of interactions inside loops, consider wrapping the loop in explicit transactions. Store exposes methods like runInTransaction for this purpose.

// Bad/slow, each Put runs inside a single transaction
for i in (1...1000) {
box.put(AnEntity(number: i))
}
// Possible, but still inefficient
store.runInTransaction {
for i in (1...1000) {
box.put(AnEntity(number: i))
}
}
// Much better
let allEntities: [AnEntity] = (1...1000).map(AnEntity.init(number:))
box.put(allEntities)

For details, check the Transaction guide and the API docs for Store for details.