Get Started with ObjectBox Swift
Learn how to use ObjectBox NoSQL DB to persist data with swift for an Offline-first iOS app experience. ObjectBox performs well on all CRUD operations and is fully ACID compliant.
Add ObjectBox to your project
See Install ObjectBox if you haven't already. This guide assumes ObjectBox was added using CocoaPods.
Define Entity Classes
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:
Conform to the
Entity
protocol oradd
// 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:
That is all you need to get going.
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.
Generate ObjectBox code
Next, some binding code needs to be generated based on the model defined in the previous step. This step is different, depending on if a CocoaPods or Swift Package setup is used.
CocoaPods
Build your project to generate the classes and Store
initializer required to use ObjectBox, for example using Product > Build in Xcode.
Next, review and keep the generated files.
Swift Package
The Swift Package integrates ObjectBox generator as a command plugin.
The generator requires write permissions in your project directory to generate the model file and Swift binding code for your entities.
To run the generator from Xcode
right-click your project in the Project navigator and click ObjectBoxGeneratorCommand,
select the target that contains your ObjectBox entity classes,
when asked, allow the command to change files.
Once the command has finished, add the generated source file (
generated/EntityInfo-<target-name>.generated.swift
) to your project.
To run the generator from the command line
Use this command:
Review and keep generated files
Among other files ObjectBox generates a JSON model file, by default to model-<target-name>.json
where <target-name>
is the name of an Xcode target, e.g. NotesExample-iOS
.
The JSON file is not visible by default in the Xcode Project navigator, you have to add it to the project or view it in Finder.
This JSON file changes when you change your entity classes (or sometimes with a new version of ObjectBox).
Keep this JSON file, commit the changes to version control!
This file keeps track of unique IDs assigned to your entities and properties. This ensures that an older version of your database can be smoothly upgraded if your entities or properties change.
The model file also enables you to keep data when renaming entities or properties or to resolve conflicts when two of your developers make changes at the same time.
Create 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 in a folder on disk. Usually for the lifetime of your app.
Getting "Missing argument for parameter 'model'..." here? Make sure to generate ObjectBox code first. Background: The ObjectBox code generator creates a second, convenience Store() initializer without the model parameter.
Of course, you would usually save your database in one of the standard system directories, like .applicationSupportDirectory
, .documentsDirectory
or .cachesDirectory
:
Basic Box operations
Since ObjectBox is all about sticking objects in boxes, you interact with objects using aBox
interface. 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
.
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
put
to insert or update objects. When put succeeds, an ID will be assigned to the entity. There areput
variants that support writing multiple objects at once, which is more efficient than writing each with its own call toput
.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, useall
.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.
Put with structs
Structs basically work the same way as classes. However, since structs are value types, ObjectBox can only adjust their ID if you pass them by reference. So if you have a mutable struct, remember to pass it by reference:
Alternately, you can manually update the struct's ID field by using putAndReturnID()
or putAndReturnIDs()
to get the ID a struct was written as:
Given immutable structs are such a common occurrence, ObjectBox generates a convenience method for you to help with updating the ID on an immutable struct, put(struct:)
, which will automatically create a new copy of your struct with the ID filled out:
Note that, after writing exampleEntity
, you must use newEntity
from then on. If you called put(struct:)
or put()
on exampleEntity again, ObjectBox would not know that this object has already been saved, and would write a second copy of it to the database.
But what if you know you already saved an immutable entity, and you already made a copy because you changed one of its fields, and don't need another copy? Then you can call put()
, just like above:
So beyond having to use a special call the first time you write out an entity, everything is the same as with classes.
For ObjectBox to work with structs, there needs to be an init()
method on your struct that accepts all its persisted properties. In the above example, the default initializer provided for the struct by Swift does just fine, but if you have properties that are not persisted, or you are defining your own initializer, you may also have to provide that initializer.
Note that for structs you will usually not want to specify a default value of 0 for the ID like you do for classes. If you do, the default initializer will omit the "id:" parameter and there would be no way to initialize the ID without writing your own initializer.
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 (likeput([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.
For details, check the Transaction guide and the API docs for Store for details.
Last updated