我用 SQL 数据库创建了一个字典应用程序,但问题是用户在UISearchBar
搜索过程中搜索单词时非常慢!为什么会这样?这是我的代码:
- (void)updateSearchString:(NSString*)aSearchString
{
[self.myTable reloadData];
}
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
searchbar.showsCancelButton = YES;
if([searchText length] > 0) {
dbClass=[[DB alloc]init];
[dbClass searchWord:searchText];
}else
{
dbClass=[[DB alloc]init];
[dbClass searchWord:@""];
}
[self.myTable reloadData];
}
表视图代码:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
appClass = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSLog(@"%d",appClass.wordList.count);
return appClass.wordList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
appClass = (AppDelegate *)[[UIApplication sharedApplication] delegate];
readerClass = (Reader *)[appClass.wordList objectAtIndex:indexPath.row];
cell.textLabel.text = readerClass.Name;
return cell;
}
编辑:
-(void)searchWord:(NSString *)txt{
NSMutableArray *DB_Array = [[NSMutableArray alloc] init];
NSString *dbPath=[self getDBPath];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
NSString *sql =[NSString stringWithFormat:@"SELECT * FROM DIC Where Name LIKE \'%@%%\' ",txt];
// NSLog(@"%@",sql);
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, [sql UTF8String] , -1, &compiledStatement, NULL) == SQLITE_OK) {
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
NSInteger oid = sqlite3_column_int(compiledStatement, 0);
const char* f1 = (const char*)sqlite3_column_text(compiledStatement, 1);
NSString *oName = f1 == NULL ? nil : [[NSString alloc] initWithUTF8String:f1];
const char* f2 = (const char*)sqlite3_column_text(compiledStatement, 2);
NSString *oMean = f2 == NULL ? nil : [[NSString alloc] initWithUTF8String:f2];
const char* f3 = (const char*)sqlite3_column_text(compiledStatement, 3);
NSString *oPron = f3 == NULL ? nil : [[NSString alloc] initWithUTF8String:f3];
NSInteger bm = sqlite3_column_int(compiledStatement, 5);
readerClass = [[Reader alloc]initWithReadDB:oid Name:oName Mean:oMean Pron:oPron bookMark:bm];
[DB_Array addObject:readerClass];
}
}
else {
NSLog(@"Error retrieving data from database.");
}
sqlite3_close(database);
}
else {
NSLog(@"Error: Can't open database!");
NSLog(@" DB Name %@",viewController.dbName);
}
AppDelegate *appDelegateClass = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegateClass.wordList removeAllObjects];
[appDelegateClass.wordList=DB_Array mutableCopy];
}