Skip to content

Models in 2.0

Jens Alfke edited this page May 8, 2017 · 2 revisions

Some design notes for re-implementing model objects in CBL 2.0.

Goals

  • Don't require a fixed base class — developers may want to have their own.
  • Allow nested models — models based on subdocuments.
  • Better performance.
    • Read/write Fleece directly without expanding the entire doc to an Obj-C object tree.
    • Make models independent of CBLDocuments, at least for property access.

Design

CBLModel

Models are declared as protocols, inheriting from a base CBLModel protocol we provide. This is mostly a placeholder, but it does declare a database property that associates the model with a database.

Any class that implements a model protocol can be used as a model class. We will provide a base model class as a convenience, which will provide some useful methods like -save:.

Properties

All properties declared in model protocols (except for CBLModel itself) are considered persistent. Properties declared directly in a model class are not persistent.

The latter rule might be confusing, but I think model classes will often have transient properties, and without this rule there's no clear way to tell whether a property declared in a class is meant to be persistent or not.

The persistent properties must be synthesized (the compiler will do this automatically by default.)

Using @synthesize instead of @dynamic is a change from 1.x. It lets us take advantage of the efficient getter/setter methods created by the compiler, which access an instance variable. Otherwise we'd have to provide side storage of our own, or dynamically translate the Fleece value into Objective-C every time the getter is called.

If there's an explicit @synthesize directive that specifies an instance variable name, e.g. @synthesize length=Length, then that variable name (minus any "_" prefix) will be used as the document (JSON) property name, instead of the Objective-C property's name.

The custom naming is a bit of a hack, but it's an easy way to let developers use different property names, which is important if the JSON property name would be illegal as an Obj-C property name, e.g. id or class. However, this still doesn't solve the problem of a JSON property that's not a valid C identifier, like zip code, *, or erklärung.

Inheritance

  • Model protocols can inherit from (one or more) other model protocols, not just directly from CBLModel.
  • Model protocols can inherit from non-model protocols as well; properties inherited from them are not persistent.
  • Model classes can implement more than one model protocol.

CBLModelFactory

As in 1.x, the class CBLModelFactory manages models for a database. It's reachable from the database's modelFactory property.

In 2.0 the factory has additional responsibilities: models with custom base classes won't inherit methods like -save: or -revert:, so the factory needs to provide them.