-
Notifications
You must be signed in to change notification settings - Fork 364
Hello World
robbiehanson edited this page Mar 20, 2013
·
11 revisions
"Hello World", YapDatabase style:
// Create and/or Open the database file
YapDatabase *database = [[YapDatabase alloc] initWithPath:databasePath];
// Get a connection to the database (can have multiple for concurrency)
YapDatabase *connection = [database newConnection];
// Add an object
[connection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
[transaction setObject:@"Hello" forKey:@"World"];
}];
// Read it back
[connection readWithBlock:^(YapDatabaseReadTransaction *transaction) {
NSLog(@"%@ World", [transaction objectForKey:@"World"]);
}];
As you might guess, you can do a whole bunch of stuff within a single transaction block. For example, you can do batch inserts, or enumerate all objects in the database.
A transaction represents a single atomic operation to the database. Furthermore a read-only transaction represents an immutable snapshot-in-time of the database. Even if another connection makes changes to the data, those changes don't affect an in-progress read-only transaction. Thus your data maintains in a consistent state.
Concurrency is straight-forward. Here are the rules:
- You can have multiple connections.
- Every connection is thread-safe.
- You can have multiple read-only transactions simultaneously without blocking.
- You can have multiple read-only transactions and a single read-write transaction simultaneously without blocking.
- There can only be a single read-write transaction at a time. Read-write transactions go through a serial queue.
- There can only be a single transaction per connection at a time. Transactions go through a per-connection serial queue.
Here's how simple it is to add concurrency:
- (void)viewDidLoad
{
connection = [database newConnection]; // For main thread (e.g. cellForIndexPath)
backgroundConnection = [database newConnection]; // Spice it up with concurrency
}
- (void)dataDidDownload:(NSArray *)objects
{
// Perform updates on background thread.
// The 'backgroundConnection' won't block the separate 'connection',
// so the user can continue scrolling as fast as possible.
// Furthermore the 'asyncTransaction' makes it dead-simple for us.
[backgroundConnection asyncReadWriteWithTransaction:^(YapDatabaseReadWriteTransaction *transaction) {
for (id object in objects) {
[transaction setObject:object forKey:object.key];
}
} completionBlock:^{
// Back on the main thread, let's update our view
[self newDataAvailable];
}];
}