我有很多行需要插入到数据库中。我下载了大约 50 个以制表符分隔的 .txt 文件,其中包含我需要的信息。我解析数据并以相同的方法将其插入数据库。当我将它作为单独的方法使用时,我的 27" iMac 上的模拟器会因为内存不足而崩溃。该方法如下所示:
- (BOOL)insertDataWithFileName:(NSString *)fileName {
NSLog(@"%s %@", __FUNCTION__, fileName);
if (_db == nil) {
return NO;
}
// Get the data from the file
NSData *data = [[NSData alloc] initWithContentsOfFile:[[self applicationDocumentsDirectory] stringByAppendingPathComponent:fileName]];
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// Parse each line by newlines first
NSArray *lines = [responseString componentsSeparatedByString:@"\n"];
NSString *ID = [[fileName componentsSeparatedByString:@"."] objectAtIndex:0];
// Set up the database insert statement
NSString *tableName = @"Hardcodedtablename"; // remove after prototype
BOOL oldshouldcachestatements = _db.shouldCacheStatements;
[_db setShouldCacheStatements:YES];
[_db beginTransaction];
NSString *insertQuery = [NSString stringWithFormat:@"INSERT INTO %@ values(null, ?, ?, ?, ?, ?, ?, ?);", tableName];
BOOL success;
// Parse each line by tabs
for (NSString *line in lines) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *fields = [line componentsSeparatedByString:@"\t"];
// Need to check since some of the .txt files have an empty newline at the EOF.
if ([fields count] == NUM_VARIANT_FIELDS) {
NSNumber *loc = [NSNumber numberWithInteger:[[fields objectAtIndex:0] integerValue]];
NSString *carType = [fields objectAtIndex:1];
NSString *model = [fields objectAtIndex:2];
NSString *AA = [fields objectAtIndex:7];
NSString *BB = [fields objectAtIndex:8];
NSNumber *freq = [[fields objectAtIndex:11] isEqualToString:@""] ? [NSNumber numberWithDouble:-1.0] : [NSNumber numberWithDouble:[[fields objectAtIndex:11] doubleValue]];
NSArray *argArray = [[NSArray alloc] initWithObjects:ID, loc, carType, model, AA, BB, freq, nil];
success = [_db executeUpdate:insertQuery withArgumentsInArray:argArray];
[argArray release];
}
[pool drain];
}
[_patientAnnotatedDatabase commit];
[_patientAnnotatedDatabase setShouldCacheStatements:oldshouldcachestatements];
return success;
}
正如您从我的 for 循环中看到的那样,在数组中的所有文件被 \t 分隔后,我实际上并不需要它。我设置了一个自动释放池来减少 for 循环中的内存占用。最大的文件中有 270,000 行。这些文件大约有 50 个。因此,在设备上的 2 个文件之后,它崩溃了。虽然没有错误消息。
我想知道此时我的选择是什么。iPad 真的可以处理这么多的数据吗?我可以对这种方法进行优化吗?
还是我必须在服务器端创建一个数据库并将数据库下载到设备上?如果我确实将数据库从服务器下载到设备,FMDB 是否支持将这些表从一个数据库传输到另一个数据库?我在谷歌搜索时找不到类似的东西。谢谢!