Search code examples
iosobjective-csqliteuisearchbaruisearchbardelegate

Searching the database entries for a String using Objective C


I'm trying to search the text entered by the user in the searchbar to check if that text is contained by any of the database entries and want to store the result into a NSMutableArray

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [search resignFirstResponder];
    [search endEditing:YES];

    str = search.text;

    app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    app.databasePath = [app getDBPath];
    const char *dbpath = [app.databasePath UTF8String];
    sqlite3_stmt *statement;

    if (sqlite3_open(dbpath, &conn) == SQLITE_OK)
    {
        NSString *strSelectQuery = [NSString stringWithFormat: @"SELECT songname FROM Songs WHERE songname LIKE '%%@%'", str];

        const char *query_stmt = [strSelectQuery UTF8String];

        if (sqlite3_prepare(conn, query_stmt, -1, &statement, NULL) == SQLITE_OK)
        {
            while (sqlite3_step(statement) == SQLITE_ROW)
            {
                [matchList addObject:[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)]];
            }
            sqlite3_finalize(statement);
        }
        sqlite3_close(conn);
    }
    NSLog(@"Total Songs : %i", [matchList count]);
}

Solution

  • The above code didn't work because i Forgot to write a Line which reloads the data after i have entered the text and clicked on the Search button of the UISEarchBar

    [_searchResultTable reloadData];

    - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
    {
        [search resignFirstResponder];
        [search endEditing:YES];
    
        str = search.text;
    
        songList = [[NSMutableArray alloc] init];
    
        app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
        app.databasePath = [app getDBPath];
        const char *dbpath = [app.databasePath UTF8String];
        sqlite3_stmt *statement;
    
        if (sqlite3_open(dbpath, &conn) == SQLITE_OK)
        {
            NSString *strSelectQuery = [NSString stringWithFormat: @"SELECT * FROM Songs WHERE songname LIKE '%%%@%%'", str];
            const char *query_stmt = [strSelectQuery UTF8String];
    
            if (sqlite3_prepare(conn, query_stmt, -1, &statement, NULL) == SQLITE_OK)
            {
                while (sqlite3_step(statement) == SQLITE_ROW)
                {
                    [songList addObject:[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)]];
                }
                sqlite3_finalize(statement);
            }
            sqlite3_close(conn);
        }
    
        [_searchResultTable reloadData];
    }