我已经实现了NSOPERATIONQUEUE通过发送请求,我可以从服务器下载响应,但问题是我无法并行处理sqlite插入/更新响应,我得到数据库锁定错误。所以任何人都可以建议我使用数据库来插入/更新我下载的响应的解决方案??
我已经创建了一个NSOperation类作为PageLoadOperation,我将请求7次传递给该NSOperation类并将其添加到队列中,如下所示
PageLoadOperation *pageLoad=[[PageLoadOperation alloc]initWithRequest:theRequest];
[queue addOperation:pageLoad];
在Main我可以通过以下NSURLConnection发送请求
[NSURLConnection sendAsynchronousRequest:theRequest
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
[self openConnection];
[self doSomethingWithData:data];
[self closeConnection];
}];
在doSomethingWithData方法中,我将通过将数据转换为NSString来插入/更新响应我已经单独创建了打开数据库连接的方法,一旦插入/更新完成,我将通过以下方法关闭连接
-(BOOL)openConnection
{
database=nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
documentsDir = [paths objectAtIndex:0];
if(sqlite3_open([[documentsDir stringByAppendingPathComponent:@"DataStore"] UTF8String], &database)==SQLITE_OK)
{
NSLog(@"DB Connection Established successfully");
return YES;
}
else
{
NSLog(@"DB not connected");
return NO;
}
}
-(BOOL)closeConnection
{
NSLog(@"%@",documentsDir);
if(sqlite3_close(database)==SQLITE_OK)
{
NSLog(@"DB Connection closed successfully");
return YES;
}
else
{
NSLog(@"Error Failed to close DB because %s",sqlite3_errmsg(database));
return NO;
}
}
我的插入方法是:
- (void) addToDatabase :(NSString*) sqlstmt :(NSArray *)params
{
sqlite3_stmt *addStmt;
if(sqlite3_prepare_v2(database, [sqlstmt UTF8String], -1, &addStmt, NULL) != SQLITE_OK)
NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
else
{
for (i=1; i<=[params count]; i++)
{
sqlite3_bind_text(addStmt, i,[[params objectAtIndex:i-1] UTF8String], -1, SQLITE_TRANSIENT);
}
}
if(SQLITE_DONE != sqlite3_step(addStmt))
NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
else
NSLog(@"%lld",sqlite3_last_insert_rowid(database));
sqlite3_finalize(addStmt);
}
在添加到数据库时,我收到数据库锁定错误,因为当一个响应打开数据库并并行插入数据库时,另一个响应尝试打开数据库连接,那么我该如何解决这个问题呢?