在后台插入sqlite数据库表中的数据

时间:2012-08-20 12:12:19

标签: iphone

我需要在后台的表中插入数据。我使用NSTimer在sqlite数据库的表中插入数据。但它在插入过程中冻结了应用程序。我也使用NSThread但它也创造同样的问题。我正在分享我正在使用的代码:

[NSTimer scheduledTimerWithTimeInterval:0.0 target:self selector:@selector(InsertDataInTable) userInfo:nil repeats:NO];

-(void)InsertDataInTempTable
{
        DatabaseManager *objDb=[[DatabaseManager alloc]init];
        [objDb setDelegate:self];
        for(int i=0;i<[arrayTempTableData count];i++)
        {
            [objDb savedata:[dictCurrentUrlInfo objectForKey:TempTableName] elements:[arrayTempTableData objectAtIndex:i]];
        }
}

#pragma mark -
#pragma mark Save Operation

-(void)savedata:(NSString *)into elements:(NSMutableDictionary *)dictInsert{
        NSString *sql_String = @"";
        if([into isEqualToString:TABLEFirstAidTemp])
        {
            sql_String = [NSString stringWithFormat:@"INSERT INTO %@ VALUES('%@', '%@', '%@')", into,[dictInsert objectForKey:@"ArticleNumber"],[dictInsert objectForKey:@"ArticleTitle"],[dictInsert objectForKey:@"ArticleCategory"]];
        }
        sqlite3_exec(sql_Database1, [sql_String UTF8String], nil, nil, nil);
}

请为我提供一个解决此问题的正确解决方案。我想在后台执行表格中插入数据。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

解决方案是使用NSThread。也许你错了。

您的代码将如下所示

-(void)InsertDataInTempTable
{
       [NSThread detachNewThreadSelector:@selector(InsertingData) toTarget:self withObject:nil];
}

-(void)InsertingData
{
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        DatabaseManager *objDb=[[DatabaseManager alloc]init];
        [objDb setDelegate:self];
        for(int i=0;i<[arrayTempTableData count];i++)
        {
            [objDb savedata:[dictCurrentUrlInfo objectForKey:TempTableName] elements:[arrayTempTableData objectAtIndex:i]];
        }
        [pool release];
}

#pragma mark -
#pragma mark Save Operation

-(void)savedata:(NSString *)into elements:(NSMutableDictionary *)dictInsert{
        NSString *sql_String = @"";
        if([into isEqualToString:TABLEFirstAidTemp])
        {
            sql_String = [NSString stringWithFormat:@"INSERT INTO %@ VALUES('%@', '%@', '%@')", into,[dictInsert objectForKey:@"ArticleNumber"],[dictInsert objectForKey:@"ArticleTitle"],[dictInsert objectForKey:@"ArticleCategory"]];
        }
        sqlite3_exec(sql_Database1, [sql_String UTF8String], nil, nil, nil);
}