您的位置:首页 > 其它

深入了解FMDB<二>

2016-01-29 17:29 253 查看
继上篇我们讲了什么是FMDB,和通过FMDB创建数据库,以及数据库的一些属性的获取,,大体上就是讲解FMDB的第一个重要的类,FMDatabase,今天这篇我们还是接着讲解

这次我们着重讲解FMDB的第二个重要的类:FMDatabaseQueue,

/*Using a single instance of `<FMDatabase>` from multiple threads at once is a bad idea. It has always been OK to make a `<FMDatabase>` object *per thread*. Just don't share a single instance across threads, and definitely
not across multiple threads at the same time.*/

使用单例在不同的线程中操作不是好的办法。它将会在每一个线程中都创建一个FMDatabase对象,千万不要在多个线程中共享一个单例。所以说呢,我们引进了FMDatabaseQueue,

First, make your queue. 首先,就是创建一个线程队列:

FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath];

Then use it like so:

[queue inDatabase:^(FMDatabase *db) {

[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]];

[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]];

[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]];

FMResultSet *rs = [db executeQuery:@"select * from foo"];

while ([rs next]) {

//…

}

}];

An easy way to wrap things up in a transaction can be done like this:

[queue inTransaction:^(FMDatabase *db, BOOL *rollback) {

[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]];

[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]];

[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]];

if (whoopsSomethingWrongHappened) {

*rollback = YES;

return;

}

// etc…

[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:4]];

}];

`FMDatabaseQueue` will run the blocks on a serialized queue (hence the name of the class). So if you call `FMDatabaseQueue`'s methods from multiple threads at the same time, they will be executed in the order
they are received. This way queries and updates won't step on each other's toes, and every one is happy.

FMDatabaseQueue将会在一个串行队列中执行block。所以说如果你同时在多个线程中调用FMDatabaseQueue里边的方法,它们将会按照它们接收到的顺序而有秩序的执行,不会说出现堵塞线程之类的问题。

/** Create queue using path.

@param aPath The file path of the database.
通过一个文件路径来创建队列

@return The `FMDatabaseQueue` object. `nil` on error.

*/

+ (instancetype)databaseQueueWithPath:(NSString*)aPath;

/** Returns the Class of 'FMDatabase' subclass, that will be used to instantiate database object.

Subclasses can override this method to return specified Class of 'FMDatabase' subclass.

@return The Class of 'FMDatabase' subclass, that will be used to instantiate database object.

*/

返回FMDatabase子类

+ (Class)databaseClass;

好了,下篇继续。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: