Posted by Leah Culver on March 31, 2014
When creating apps, it's common to want to start with some initial data. The Dropbox Datastore API provides a method, getOrInsert, that makes this super easy.
For example, our game Click the Box displays the user's current level using the Datastore API. Click the Box has a datastore with a record called current_level and a field called level. The level field should start with an initial value of 0 since the user hasn't played any levels yet.
By using getOrInsert, we will either fetch an existing record or insert a new record with (optional) initial data if the record doesn't exist. Perhaps more importantly, getOrInsert is the only way to specify a record ID when inserting a record. Normally when inserting a record, the Datastore API chooses a unique ID for you, but in this case, we want to make sure our record always has the same ID. This way, even if two devices create the record while offline, the result of conflict resolution will still just be a single record.
Here's the relevant code in Click the Box:
var table = datastore.getTable('state');
var record = table.getOrInsert('current_level', { level: 0 });
DBTable *table = [self.store getTable:@"state"];
DBRecord *record = [table getOrInsertRecord:@"current_level" fields:@{@"level": @0} inserted:nil error:nil];
DbxTable table = datastore.getTable("state");
DbxRecord record = table.getOrInsert("current_level", new DbxFields().set("level", 0));