-
Notifications
You must be signed in to change notification settings - Fork 2
Collections
Sometimes key/value just doesn't cut it. What you really want is collection/key/value.
We've got a database for that.
- YapDatabase = Key/Value
- YapCollectionsDatabase = Collection/Key/Value
YapCollectionsDatabase is very similar to YapDatabase. But YapCollectionsDatabase uses an extra column in the underlying sqlite database table to store the collection. As such, the queries can be optimized for the collection, key or both. Additionally YapCollectionsDatabase has a separate API that reflects its usage in dealing with collections. For example:
/**
* Returns the total number of collections.
* Each collection may have 1 or more key/object pairs.
**/
- (NSUInteger)numberOfCollections;
/**
* Returns the total number of keys in the given collection.
* Returns zero if the collection doesn't exist (or all key/object pairs from the collection have been removed).
**/
- (NSUInteger)numberOfKeysInCollection:(NSString *)collection;
/**
* Object access.
* Objects are automatically deserialized using database's configured deserializer.
**/
- (id)objectForKey:(NSString *)key inCollection:(NSString *)collection;
/**
* Fast enumeration over all keys in the given collection.
*
* This uses a "SELECT key FROM database WHERE collection = ?" operation,
* and then steps over the results invoking the given block handler.
**/
- (void)enumerateKeysInCollection:(NSString *)collection
usingBlock:(void (^)(NSString *key, BOOL *stop))block;You can see the full API by looking at the YapCollectionsDatabaseTransaction header file
When you have groups of related, but separate, data then YapCollectionsDatabase may be the way to go. That way you can use a single database file, and reduce your overhead while you're at it.
For example: You're storing top-level posts, and related comments. Each group of comments is related to a single post. So that group of comments could use the postId as its collection.
How many posts do I have?
NSUInteger postsCount = [transaction numberOfKeysInCollection:nil];(Passing nil as the collection is the same as passing an empty string.)
How many comments are there for this post?
NSUInteger commentsForPostCount = [transaction numberOfKeysInCollection:post.uuid];