Основные вопросы поиска данных iOS 5 - PullRequest
0 голосов
/ 06 февраля 2012

Используя основные данные, данные выбираются правильно и отображаются правильно, проблема заключается в поиске, что он не фильтрует результаты, что бы я ни набрал в строке поиска, он показывает то же самое представление таблицы с теми же данными в отфильтрованном результаты ..

- (void)viewDidLoad
{
    [super viewDidLoad];

    if (context == nil) 
    { 
        context = [(VektorAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; 
    }    
    app = [[UIApplication sharedApplication] delegate];

     [self getData];

    // create a filtered list that will contain products for the search results table.

    filteredListItems = [[NSMutableArray alloc] initWithCapacity:[self.plateNumbers count]];

    // restore search settings if they were saved in didReceiveMemoryWarning.
    if (self.savedSearchTerm){
        [self.searchDisplayController setActive:self.searchWasActive];
        [self.searchDisplayController.searchBar setSelectedScopeButtonIndex:self.savedScopeButtonIndex];
        [self.searchDisplayController.searchBar setText:savedSearchTerm];

    self.savedSearchTerm = nil;
    }
}

Извлечение данных из основных данных:

-(void)getData {

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Favouritesdata" inManagedObjectContext:context];

NSFetchRequest *request = [[NSFetchRequest alloc] init];

[request setFetchBatchSize:20];

[request setEntity:entity];

NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"licenseplate" ascending:NO];

NSArray *newArray = [[NSArray alloc]initWithObjects:sort, nil];

[request setSortDescriptors:newArray];

NSLog(@"newArray: %@", newArray);

NSError *error;

results = [[context executeFetchRequest:request error:&error] mutableCopy];

plateNumbers = [results valueForKey:@"licenseplate"];

NSLog(@"plateNumbers: %@", plateNumbers);

[self setLicensePlateArray:results];

[self.favouritesTable reloadData];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == favouritesTable) {
    return [licensePlateArray count];
} else { // handle search results table view
    return [filteredListItems count];
    }      
}

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

if (tableView == favouritesTable) {
    cellValue = [licensePlateArray objectAtIndex:indexPath.row];
} else { // handle search results table view
    cellValue = [filteredListItems objectAtIndex:indexPath.row];
}

static NSString *CellIdentifier = @"vlCell";

VehicleListCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

    NSLog(@"Cell Created");

    NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"VehicleListCell" owner:nil options:nil];

    for (id currentObject in nibObjects) {
        if ([currentObject isKindOfClass:[VehicleListCell class]]) {
            cell = (VehicleListCell *)currentObject;
        }
    }
    NSInteger cellVal = indexPath.row;

    NSLog(@"indexPath.row: %i", cellVal);

    UILongPressGestureRecognizer *pressRecongnizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(tableCellPressed:)];
    pressRecongnizer.delegate = self;
    pressRecongnizer.minimumPressDuration = 0.5f;
    [cell addGestureRecognizer:pressRecongnizer];
    [pressRecongnizer release];
}

cell.textLabel.font = [UIFont systemFontOfSize:10];

Favouritesdata *favdata = [results objectAtIndex:indexPath.row];

cell.licPlate.text = [favdata licenseplate];

NSLog(@"cellvalue for cellforRow: %@", cell.licPlate.text);

return cell;
}

Реализация панели поиска:

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{       
    NSPredicate *resultPredicate = [NSPredicate 
                                    predicateWithFormat:@"SELF contains[cd] %@",
                                    searchText];

    self.filteredListItems = [self.plateNumbers filteredArrayUsingPredicate:resultPredicate];

}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
   /* [self filterContentForSearchText:searchString scope:
     [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
    */

    if ([[searchString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length])
        self.favouritesTable = controller.searchResultsTableView;

    return YES;
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption {
    [self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:
     [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
    return YES;
}

Как решить эту проблему?

1 Ответ

0 голосов
/ 06 февраля 2012

Просто сделайте код ясным и определите все методы, вы просто устанавливаете предикат, а не запускаете его запрос.

просто создайте отдельный метод и просто передайте поисковый текст в качестве параметра этому методу для запроса предиката и запроса выборки, а затем перезагрузите таблицу.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...