Skip to content

Guide: Models

Jens Alfke edited this page Aug 8, 2012 · 6 revisions

TABLE OF CONTENTS

9. Data Models

CouchCocoa has a object modeling layer that can make it easier to integrate TouchDB documents into your code. It's somewhat similar to, though simpler than, CoreData's NSManagedObject. The idea is the same: it allows you to create Objective-C classes whose instances represent documents in the database, and whose native properties map to document properties.

Defining A Model Class

To create a model class, you subclass CouchModel. Here's an example:

// ShoppingItem.h
#import <CouchCocoa/CouchCocoa.h>

@interface ShoppingItem : CouchModel
@property bool check;
@property (copy) NSString* text;
@property (retain) NSDate* created_at;
@end

Here's the implementation:

// ShoppingItem.m
#import "ShoppingItem.h"

@implementation ShoppingItem
@dynamic check, text, created_at;
@end

Yes, that's all it takes. The accessors for the properties will be hooked up at runtime and will get and set the properties of the same names in the associated TouchDB document. The @dynamic directive in the .m file is just there to keep the compiler from complaining that the properties aren't implemented at compile time.

Using A Model Class

Now that we have a model class, how do we use it? If we have a CouchDocument, we can get a model object corresponding to it by calling +modelForDocument:

CouchDocument* doc = ...... ;
ShoppingItem* item = [ShoppingItem modelForDocument: doc];

Or we can create a new unsaved model object:

	ShoppingItem* item = [[ShoppingItem alloc] initWithNewDocumentInDatabase: database];

We can access the document properties natively:

NSLog(@"Text is %@", item.text);
item.check = true;

Model properties are observable, so you on Mac OS you can bind them to UI controls.

You can access any document property, whether or not you've declared an Objective-C property for it. Just be aware that these values are always accessed in object form, without automatic conversion to and from scalar types:

NSNumber* priorityObj = [item getValueOfProperty: @"priority"];
int priority = priorityObj.intValue;

Saving Changes

Property changes affect the state of the CouchModel object but aren't immediately saved to the document or the database. To do so, you have to save the model:

RESTOperation* op = [item save];
[op wait];    // if you want to save synchronously

If you set the model's autosaves property to true, it will save changes automatically. Not after every single property change, but within a brief time after one or more changes.

Finally, call deleteDocument to delete:

RESTOperation* op = [item deleteDocument];
[op wait];    // if you want to delete synchronously

More About Property Types

The automatic mapping from Objective-C types to JSON document properties is very useful, but it has some details and limitations you should be aware of.

  • JSON types: Of course all the object types used to represent JSON are supported: NSNumber, NSNull, NSString, NSArray, NSDictionary.
  • Scalars: Numeric properties can be declared as ordinary C numeric types like int or double and CouchModel will automatically "box" them into NSNumber objects.
  • bool vs. BOOL: You should declare boolean properties as type bool, not BOOL. (The reason is that BOOL is just a typedef for char, so at runtime it's impossible to tell a BOOL value apart from an integer, which means CouchModel will store them in JSON as 0 and 1, not false and true.)
  • NSData: As an extension, you can declare properties of type NSData. CouchModel will save such a value by base64-encoding it into a JSON string, and read it by base64-decoding the string.
  • NSDate: Similarly, NSDate-valued properties are converted to and from JSON strings using the ISO-8601 date format. (Be aware that if you're reading documents generated externally that didn't store dates in ISO-8601, CouchModel won't be able to parse them. You'll have to change the property type to NSString, and use an NSDateFormatter to do the parsing yourself.)

And finally, properties can point to other models...

Relationships Between Models

So far we've seen properties whose values are JSON types like integers, strings or arrays. CouchModel also supports properties whose values are pointers to other CouchModel objects. This creates what are generally called "relationships" between objects. For example, a blog comment would probably have a relationship to the post that it refers to.

In the actual document, a relationship is expressed by a property whose value is the ID of the target document. CouchModel knows this convention, so if you simply declare an Objective-C dynamic property whose type is a pointer to a CouchModel subclass, then at runtime the property value is looked up like this:

Objective-C property --> document property --> database (by ID) --> document --> model

Example

Let's say you have documents for blog comments, and each has a "post" property whose value is the document ID of the blog post it refers to. You can model that like this:

@class BlogPost;

@interface BlogComment : CouchModel
@property (assign) BlogPost* post;
@end

And in the implementation of BlogComment you simply declare the property as @dynamic, like any other model property.

Note that the declaration uses (assign) instead of the more typical (retain). This is because a relationship to another model doesn't retain it, to avoid creating reference-loops that can lead to memory leaks.

Relationships To Untitled Documents

There's a slight gotcha with this. To save a model object that has a relationship, the document property has to be updated with the ID of the target document. But by default, documents are created "untitled", with no ID until the first time they're saved. In that case, the target document has to be saved first before you can save the source document that refers to it. This is awkward, and in the worst case leads to chicken-and-egg problems if you have two new documents that each refer to the other. Oops!

The solution to this is to create new documents with an ID. It needs to be unique, though. There are three ways to ensure this:

  • Get an ID from the server by calling -[CouchServer generateUUIDs: 1]
  • Create an ID locally by calling CFUUIDCreate()
  • Use a pre-existing ID that you know will be unique to the database (for example, an ISBN or employee number)

Once you have the ID, you can create the model like this:

[MyModel modelForDocument: [db documentWithID: someUniqueID]]

If you instantiate your models like this, you won't have any trouble with saving relationships.

Dynamic Subclassing

So far, if you declare a property's type as being BlogPost*, the instantiated object will be a BlogPost. But what if BlogPost has subclasses? In a tumblr-style app, maybe there are different types of posts, like text / image / video, differentiated by the value of a type property, and you want these to be instantiated as subclasses like TextPost, ImagePost and VideoPost. How do you tell the property which class to instantiate for which document when the property type doesn't narrow it down to one class?

Enter the CouchModelFactory. This singleton object keeps a registry that maps document type property values to classes. If at launch time you register the type strings and the corresponding BlogPost subclasses, then CouchModel will consult this when instantiating model-reference properties. So the value of the post property of a comment will be a TextPost, ImagePost or VideoPost depending on the document's type.

Once you've started using the CouchModelFactory, you'll probably want to start instantiating models for existing documents by calling +modelForDocument: on CouchModel itself, rather than a subclass. This is because

[CouchModel modelForDocument: doc]

uses the factory to decide at runtime which class to instantiate based on the document's contents, while

[BlogPost modelForDocument: doc]

will always create a BlogPost object, even if the document's type indicates that it should get an ImagePost or VideoPost, which is probably not what you want.

Clone this wiki locally