2013-09-23 1 views
0

Я создал автоматическое полное текстовое поле. Моя проблема заключается в том, что как передать массив - это хранимое значение, которое извлекается из db . Когда вы используете _category detail, мое приложение выйдет из строя. Если я использую NSArray с объектами, проблем нет. Когда я отладки кода я нашел проблему поиска метод плз помочь решить мою проблему Спасибо большоеКак передать значение db для автоматического заполнения текста?

Моя функция

- (void)viewDidLoad 
{ 
    self.categoryDetail = [CompanyDetailDatabase database].categoryDetail; 

    NSMutableArray *arrt = [[NSMutableArray alloc]init]; 
    //arrt = [NSMutableArray arrayWithArray:_categoryDetail]; 
    arrt=[NSArray arrayWithArray:_categoryDetail]; 

    self.pastUrls = [[NSMutableArray alloc]initWithArray:arrt]; 
    // self.pastUrls = [[NSMutableArray alloc] initWithObjects:@"Hello1",@"Hello2",@"Hello3", nil]; 
    self.autocompleteUrls = [[NSMutableArray alloc] init]; 

    autocompleteTableView = [[UITableView alloc] initWithFrame:CGRectMake(20, 180, 280, 50) style:UITableViewStylePlain]; 
    autocompleteTableView.delegate = self; 
    autocompleteTableView.dataSource = self; 
    autocompleteTableView.scrollEnabled = YES; 
    autocompleteTableView.hidden = YES; 
    [self.view addSubview:autocompleteTableView]; 

    [txtProduct setDelegate:self]; 
} 
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring { 

    // Put anything that starts with this substring into the autocompleteUrls array 
    // The items in this array is what will show up in the table view 
    [autocompleteUrls removeAllObjects]; 
    for(NSString *curString in pastUrls) 
    { 
     NSRange substringRangeLowerCase = [curString rangeOfString:[substring lowercaseString]]; 
     NSRange substringRangeUpperCase = [curString rangeOfString:[substring uppercaseString]]; 
     if (substringRangeLowerCase.length !=0 || substringRangeUpperCase.length !=0) 
     { 
      [autocompleteUrls addObject:curString]; 
     } 
    } 
    autocompleteTableView.hidden =NO; 
    [autocompleteTableView reloadData]; 
} 

#pragma mark UITextFieldDelegate methods 

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 
    autocompleteTableView.hidden = NO; 

    NSString *substring = [NSString stringWithString:textField.text]; 
    substring = [substring stringByReplacingCharactersInRange:range withString:string]; 
    [self searchAutocompleteEntriesWithSubstring:substring]; 
    return YES; 
} 

#pragma mark UITableViewDataSource methods 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger) section { 
    return autocompleteUrls.count; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    UITableViewCell *cell = nil; 
    static NSString *AutoCompleteRowIdentifier = @"AutoCompleteRowIdentifier"; 
    cell = [tableView dequeueReusableCellWithIdentifier:AutoCompleteRowIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] 
       initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AutoCompleteRowIdentifier] autorelease]; 
    } 
    cell.textLabel.text = [autocompleteUrls objectAtIndex:indexPath.row]; 
    return cell; 
} 

#pragma mark UITableViewDelegate methods 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath]; 
    txtProduct.text = selectedCell.textLabel.text; 
} 

Теперь вид сцены изображения when edit textbox array value view in table view

+1

Сообщите свое имя и пароль! – Praveenkumar

ответ

0

Я не о ваших методах. Но это очень просто. Сначала вы должны вставить некоторые записи в таблицу базы данных. И, при редактировании на вашем UITextField вы должны передать текст в таблицу базы данных в качестве SQLite запроса с условиями и возвращаетесь как NSArray или NSMutableArray Некоторые фрагменты коды -

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{ 
    if (textField == listTableView) 
    { 
     recordsArray = [self getRecords:string]; 

     if ([recordsArray count] == 0 || recordsArray == NULL) 
     { 
      [[[UIAlertView alloc] initWithTitle:nil message:@"No Records Were found" delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil] show]; 
     } 
     else 
     { 
      tableV.hidden = NO; 
      [tableV reloadData]; 
     } 
    } 
    return YES; 
} 

Выше будет получить набранную строку и передать к методу базы данных getRecords с типизированной строкой.

-(NSMutableArray*)getRecords:(NSString *)srchString 
{ 
    NSMutableArray *mutArray = [[NSMutableArray alloc]init]; 

    sqlite3 *servicesDB; 
    NSString *filePath=[AppDelegate dbPath]; 

    if(sqlite3_open([filePath UTF8String], &servicesDB) == SQLITE_OK) 
    { 
     NSString *sqlStatement; 
     sqlStatement = [NSString stringWithFormat:@"SELECT * FROM Records WHERE record = '%%%@%%'", srchString]; 
     const char *sql = [sqlStatement UTF8String]; 

     sqlite3_stmt *select_statement; 
     if (sqlite3_prepare_v2(servicesDB, sql, -1, &select_statement, nil) == SQLITE_OK) 
     { 
      while (sqlite3_step(select_statement) == SQLITE_ROW) 
      { 
      char *record = (char *)sqlite3_column_text(select_statement, 0); 

      NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; 

      [dict setObject:[NSString stringWithUTF8String:record] forKey:@"record"]; 

      [mutArray addObject:[dict copy]]; 
     } 
    } 
    else 
    { 
     NSLog(@"Error while fetching data. '%s'", sqlite3_errmsg(servicesDB)); 
    } 
      sqlite3_finalize(select_statement); 
    } 
    sqlite3_close(servicesDB); 
    return mutArray; 
} 

Выше метода базы данных будет выполняться и получать данные, все из которых имеют слово независимо от того, что вы набрали. Вы можете найти информацию о LIKE разделhere

Вы получите окончательный результат после завершения выполнения. Просто найдите sample project here

Смежные вопросы