如果我的搜索谓词返回nil,则尝试弹出UIAlert

时间:2011-06-18 04:38:20

标签: core-data uialertview uisearchbar nspredicate

如果用户进行搜索并且谓词返回nil,我正在尝试弹出一条警告“没有找到记录”。

我尝试了这个,但警报永远不会被调用。我只是得到一张空的桌面视图。

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {

    if (self.sBar.text != nil){

        NSPredicate *template = [NSPredicate predicateWithFormat:@"name contains[cd] $SEARCH OR optionOne contains[cd] $SEARCH OR optionTwo contains[cd] $SEARCH"];
        NSDictionary *replace = [NSDictionary dictionaryWithObject:self.sBar.text forKey:@"SEARCH"];
        NSPredicate *predicate = [template predicateWithSubstitutionVariables:replace];

        [fetchedResultsController.fetchRequest setPredicate:predicate];

    }

    [[fetchedResultsController fetchedObjects] count];

    if (fetchedResultsController.fetchedObjects != nil) {

        //do nothing

    } else {

        //display alert
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"No records match." 
                                                           delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
            [alert release];

    }

    NSError *error = nil;
    if (![[self fetchedResultsController] performFetch:&error]) {

        // Handle error
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();  // Fail
    }           

    [self.myTable reloadData];

    [sBar resignFirstResponder];  

}

2 个答案:

答案 0 :(得分:0)

谓词没有-count。谓词is an expression that evaluates to true or false。就是这样。

您可以向NSFetchedResultsController询问-fetchedObjects(返回数组),然后向该数组询问-count,但只能在调用-performFetch:后执行此操作1}}。

答案 1 :(得分:0)

哈哈!得到了......

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {

    if (self.sBar.text != nil) {

        NSPredicate *template = [NSPredicate predicateWithFormat:@"name contains[cd] $SEARCH OR optionOne contains[cd] $SEARCH OR optionTwo contains[cd] $SEARCH"];
        NSDictionary *replace = [NSDictionary dictionaryWithObject:self.sBar.text forKey:@"SEARCH"];
        NSPredicate *predicate = [template predicateWithSubstitutionVariables:replace];

        [fetchedResultsController.fetchRequest setPredicate:predicate];

    }

    NSError *error = nil;
    if (![[self fetchedResultsController] performFetch:&error]) {

        // Handle error
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        exit(-1);  // Fail
    } 

    if ([[fetchedResultsController fetchedObjects] count] != 0)  {

        [self.myTable reloadData];
        [sBar resignFirstResponder];  

    }
    else {

        //display alert
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"No records match." 
                                                           delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
            [alert release];

    }   
}