ObjectBox Swift Documentation

repository·main·Indexed 20 days ago

https://github.com/objectbox/objectbox-swift

A high-performance, on-device NoSQL database for Swift, optimized for iOS and macOS. ObjectBox supports object persistence, vector embeddings for Edge AI, and built-in relations for offline-first applications. It features a code generator based on Sourcery to avoid reflection and ensure optimal runtime performance. The library provides a Swift API wrapping the ObjectBox C API, utilizing core abstractions such as Store, Box, Entity, Id, and Query for CRUD operations and type-safe querying.

Tokens
4.2K
Snippets
15
Records
23
Agent score
70%

What's inside ObjectBox Swift

  1. Core concepts of ObjectBox Swift

    main

    ObjectBox Swift uses several key abstractions to manage data persistence:

    • Store: The central database entry point. You use it to initialize the database and obtain instances of Boxes.
    • Box: The primary interface for a specific type. Use a Box to persist objects, remove them, or create Querys.
    • Entity: A protocol you must implement on your Swift types to mark them as persistable by ObjectBox.
    • Id: A unique identifier used to distinguish object instances within the database.
    • Query: An object used to perform conditional fetching of specific types of objects based on defined criteria.
  2. How ObjectBox code generation works

    main
    ObjectBox Swift uses generated code to ensure optimal runtime performance by avoiding reflection. It utilizes a fork of Sourcery to generate the necessary boilerplate for your entities. When using CocoaPods, this is handled via the [OBX] Update Sourcery Generated Files build phase.
  3. Formulate queries using Property-based syntax

    main

    ObjectBox allows you to build queries using Property objects generated for your entities. You can use these properties inside a Box.query(_:) block to define conditions. Conditions are type-specific based on the Property.ValueType (e.g., String, Int).

    You can use explicit method calls like isEqual(to:) or use standard Swift operators for more concise syntax.

    // Using explicit method calls
    try store.box(for: Person.self).query {
        Person.name.isEqual(to: "Steve", caseSensitiveCompare: true)
    }.build()
    
    // Using concise operator syntax
    try store.box(for: Person.self).query {
        .name == "Steve"
    }.build()
  4. Run unit tests with an in-memory database

    main

    You can run unit tests using an in-memory database by setting the OBX_IN_MEMORY environment variable to true before executing the test command.

    In Xcode, you can configure this by editing your scheme: go to Test -> Arguments and add the environment variable.

    Via command line:

    export OBX_IN_MEMORY=true
    make u_tests
    export OBX_IN_MEMORY=true
    make u_tests
  5. Build the ObjectBox Swift Framework

    main

    To build the framework from source, navigate to the ios-framework/ directory and use the provided Makefile commands.

    Build Steps

    1. Fetch dependencies: Downloads the necessary libObjectBoxCore libraries.
    2. Build framework: Compiles the Swift framework.
    3. Run unit tests: Executes the XCTestCase-based tests.
    cd ios-framework/
    
    # Download the ObjectBox database libraries
    make fetch_dependencies
    
    # Build the framework
    make build_framework
    
    # Run unit tests
    make u_tests
    cd ios-framework/
    make fetch_dependencies
    make build_framework
    make u_tests
  6. Install ObjectBox via Swift Package Manager

    main

    You can add ObjectBox to an Xcode project or a Package.swift manifest.

    For Xcode Projects

    1. Add a package dependency using the URL: https://github.com/objectbox/objectbox-swift-spm.
    2. Use the dependency rule "Up to Next Major Version".
    3. Add ObjectBox.xcframework to your app target. (Use ObjectBox-Sync.xcframework if you require ObjectBox Sync).

    For Swift Package Manager Manifests

    Add the dependency to your Package.swift and link the product to your target:

    // In dependencies block
    .package(url: "https://github.com/objectbox/objectbox-swift-spm.git", from: "INSERT_VERSION"),
    
    // In targets block
    .product(name: "ObjectBox.xcframework", package: "objectbox-swift-spm")
    dependencies: [
        .package(url: "https://github.com/objectbox/objectbox-swift-spm.git", from: "INSERT_VERSION"),
    ],
    targets: [
      .executableTarget(
        name: "YourApp",
        dependencies: [
            .product(name: "ObjectBox.xcframework", package: "objectbox-swift-spm")
        ]),
    ]
  7. Install ObjectBox via CocoaPods

    main
    1. Add pod 'ObjectBox' to your Podfile.
    2. Run pod install --repo-update.
    3. Run the ObjectBox setup script: Pods/ObjectBox/setup.rb. This adds a build phase [OBX] Update Sourcery Generated Files to your target.
    4. Important: Disable the User Script Sandboxing option in your Xcode project build settings to allow the generator to run.
    5. Open the .xcworkspace file instead of the .xcodeproj.

    Troubleshooting CocoaPods

    If setup fails, update your gems:

    gem update xcodeproj && gem update cocoapods && pod repo update

    On Apple Silicon (M1), also run:

    gem update ffi ethon
    # Add to Podfile
    pod 'ObjectBox'
    
    # Run installation
    pod install --repo-update
    Pods/ObjectBox/setup.rb
  8. Manage Ruby versions with rbenv

    main

    If you encounter issues with CocoaPods due to an outdated macOS Ruby version, use rbenv to install and use a specific Ruby version (e.g., 3.0.5).

    # Install rbenv and ruby-build via Homebrew
    brew update && brew install rbenv ruby-build
    
    # Check the version required by the project
    rbenv local
    
    # Install the specific version
    rbenv install 3.0.5
    
    # Verify the version
    ruby -v
    brew update && brew install rbenv ruby-build
    rbenv local
    rbenv install 3.0.5
    ruby -v
  9. Set up the ObjectBox Swift Example project

    main

    To run the official ObjectBox Swift demonstration apps (the 'Notes' example), clone the repository and open the Example directory in Xcode. The example includes both an iOS GUI application and a macOS command-line application.

    1. Clone the repository.
    2. Navigate to the Example directory.
    3. Open NotesExample.xcodeproj in Xcode.
    4. Select either the NotesExample-iOS or NotesExample-macOS scheme to run the application.
    git clone --depth=1 https://github.com/objectbox/objectbox-swift
    cd objectbox-swift/Example
    open NotesExample.xcodeproj
  10. Add binary ObjectBox dependency via Carthage

    main

    To add ObjectBox to your project using Carthage, you can use the binary distribution specification. This method is faster and uses less disk space than the standard "github" definition because Carthage does not need to check out the entire Git repository.

    WARNING

    The Carthage release is deprecated. Please refer to the main repository README for current installation methods.

    binary "https://raw.githubusercontent.com/objectbox/objectbox-swift/master/cartspec/ObjectBox.json"