0

我需要幫助。我寫的應用程序,它應該保存數據並同時顯示它們。但我有問題。兩個操作都只在主隊列中工作。我可以做什麼?謝謝!在主隊列中使用Sqlite和UI操作

我的UI代碼

dispatch_async(dispatch_get_main_queue(), ^{ 
    [self.hostView.hostedGraph reloadData]; 
}); 

我的DB代碼

-(BOOL)addNewMesurable:(Mesurable*)mesurable{ 
    if (!_database) [self createDatabase]; 
    const char *charDBpath = [_dbPath UTF8String]; 
    if (sqlite3_open(charDBpath, &_database) == SQLITE_OK) { 
     char* errorMessage; 
     sqlite3_exec(_database, "BEGIN TRANSACTION", NULL, NULL, &errorMessage); 

     NSString *query = 
     [NSString stringWithFormat:@"insert into %@ (value , date, time) values (? , ? , ?)",[Sensor sensorNameToString: 
mesurable.sensor]]; 
     sqlite3_stmt *statement; 

     if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, NULL) == SQLITE_OK) { 

      sqlite3_bind_text(statement, 1, [[mesurable.value stringValue] UTF8String], -1, NULL); 
      sqlite3_bind_text(statement, 2, [[mesurable getStrindDate] UTF8String], -1, NULL); 
      sqlite3_bind_text(statement, 3, [[mesurable getStrindTime] UTF8String], -1, NULL); 
      // 
      if(sqlite3_step(statement) != SQLITE_DONE){ 
       NSLog(@"ERROR add data from sensor - %@ ", [Sensor sensorNameToString: mesurable.sensor ]); 

      } 
      else NSLog(@"Done"); 
      sqlite3_clear_bindings(statement); 
      sqlite3_reset(statement); 
      sqlite3_exec(_database, "PRAGMA synchronous = OFF", NULL, NULL, &errorMessage); 
      sqlite3_exec(_database, "PRAGMA journal_mode = MEMORY", NULL, NULL, &errorMessage); 
     } 
     sqlite3_exec(_database, "COMMIT TRANSACTION", NULL, NULL, &errorMessage); 
     sqlite3_finalize(statement); 
     sqlite3_close(_database); 
    } 

    return YES; 
} 

回答

0

試試這個:

您可以使用DISPATCH_QUEUE_PRIORITY_LOW,_high和_DEFAULT

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{ 
    // now send the result back to the main thread so we can do 
    // UIKit stuff. u can update ur ui 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     // update your DB content 
    }); 
});