Setting Up Code Generation

OT
Last updated 6 minutes ago

If you are using CocoaPods, you do not need to do any of these steps. This is only needed if you are trying to integrate ObjectBox into a different build process.

ObjectBox uses a code generator to generate boilerplate code that passes information about your objects to the library. We chose code generation over fat inheritance trees so you can write plain Swift objects and just use these.

The code generator is included in every version after 0.6.0 of ObjectBox. Older versions require different manual setup for code generation.

Adding the Sourcery Build Phase to Your Project

In your Xcode project, add a "New Run Script Phase" and make sure it comes above the Compile Sources phase of your project. The code generator needs to generate the code you want to compile first.

We call the Build Phase "[OBX] Update Sourcery Generated Files".

Enter the following script into this build phase:

set -e
sourcery="${PROJECT_DIR}/ObjectBox/Sourcery.app/Contents/MacOS/Sourcery"
if [ -f "$sourcery" ]; then
"$sourcery" --xcode-project "${PROJECT_FILE_PATH}" --xcode-target "${TARGETNAME}" --xcode-module "${PRODUCT_MODULE_NAME}"
else
echo "error: Cannot find Sourcery in the expected location at '$sourcery'"
exit -1
fi

Depending on how you install ObjectBox, the program location (line 3) has to be changed.

The above example assumes you've extracted the files from the ObjectBox release on Github into a folder named ObjectBox next to your project. If you had a folder named external for all external dependencies next to a myproject folder that contains your project, that line might read:

sourcery="${PROJECT_DIR}/../external/ObjectBox/Sourcery.app/Contents/MacOS/Sourcery"

You get the picture. In general, it is a good idea to use project-relative paths, so anyone checking out your project can run it, no matter where they keep theire checkouts, or what their username.

Adding the Generated Files to Your Project

Build your project once, so it can create the generated/EntityInfo.generated.swift file for you. It will not contain much of interest, yet, but now that the generated/ directory and its contents exist, you can drag them into your Xcode project so they get compiled as well (make sure you add folders as "groups", not as "folder references").

You now have a working ObjectBox setup in your project and should be able to follow the rest of the instructions in our Getting Started section.