Skip to content
This repository has been archived by the owner on Mar 9, 2022. It is now read-only.

Example Snippets

snej edited this page Jul 19, 2011 · 11 revisions

CouchCocoa Example Snippets

Connecting To A Local Database (Mac OS)

This assumes that CouchDB is already running, on the default port, on the same computer. (Launching the Couchbase Server will take care of this.)

- (void) connectToDatabase {
    CouchServer *server = [[CouchServer alloc] init];
    CouchDatabase *database = [server databaseNamed: @"mydatabase"];

    RESTOperation* op = [_database create];
    if (![op wait] && op.httpStatus != 412) {
        // failed to contact the server or create the database
        // (a 412 status is OK; it just indicates the db already exists.)
    }
}

For an example of this in action, look at DemoAppController.m.

Connecting To A Local Database (iOS)

This snippet requires that your app use the Couchbase framework, which embeds a CouchDB server inside your iOS app. In this case the startup is asynchronous; the CouchbaseEmbeddedServer will call your -couchbaseDidStart: method when the server has started up, and you can then connect to it.

- (void) connectToDatabase {
    CouchbaseEmbeddedServer* cb = [[CouchbaseEmbeddedServer alloc] init];
    cb.delegate = self;
    NSAssert([cb start], @"Couchbase couldn't start! Error = %@", cb.error);
}

- (void) couchbaseDidStart: (NSURL*)serverURL {
    CouchServer *server = [[CouchServer alloc] init];
    CouchDatabase *database = [server databaseNamed: @"mydatabase"];
    RESTOperation* op = [_database create];
    if (![op wait] && op.httpStatus != 412) {
        // failed to contact the server or create the database
        // (a 412 status is OK; it just indicates the db already exists.)
    }
}
Clone this wiki locally