在表视图中删除搜索结果对象后出现奇怪的行为

姆瓦斯科

我有一个表视图,其中包含由核心数据填充的部分。我已经实现了搜索栏,但是我遇到了一些问题。为了测试它,我创建了3个核心数据对象:

1. item 2(overdue)-> OVERDUE section
2. item 1(today)-> TODAY section
3. item 3(upcoming)->UPCOMING section.

在其他SO的帮助下,比我更多的专家用户,我已经解决了搜索栏实现的一些第一个问题。其中之一是使搜索结果对象位于新部分SEARCH RESULTS(#对象)下,该部分将按预期工作。我要解决的下一个问题如下:-搜索完成后,结果对象显示在新部分的SEARCH RESULTS下,但是尝试删除对象时显示了不希望的行为,因为删除普通对象,所以我要刷卡该行从右到左并显示红色的DELETE按钮,如果我点击该按钮,则正常行为应为:1.该行再次自动向右移动。2.表被重新加载,并且删除的行不再出现。

在这种情况下,当删除结果对象行时,在点击删除按钮后,该行将保持向左滑动,除了点击取消按钮之外,无法执行其他任何操作。然后,表视图再次以其普通视图出现。删除的结果对象行肯定会被删除。这是我的代码,非常欢迎您解决此问题:

#import "ToDoItemsTableViewController.h"
#import "AppDelegate.h"
#import "AddToDoItemViewController.h"
#import "ToDoSubItemsTableViewController.h"

@interface ToDoItemsTableViewController ()

@property (nonatomic, strong)NSManagedObjectContext *managedObjectContext;
@property (nonatomic, strong)NSFetchedResultsController *fetchedResultsController;

@end

@implementation ToDoItemsTableViewController
@synthesize searchResults;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(NSManagedObjectContext *)managedObjectContext{
    return [(AppDelegate*)[[UIApplication sharedApplication]delegate]managedObjectContext];
}
- (void)viewDidLoad
{
    [super viewDidLoad];


    //navigation bar background image
    [self.navigationController.navigationBar

     setBackgroundImage:[UIImage imageNamed:@"navBar.png"]

     forBarMetrics:UIBarMetricsDefault];

    NSDictionary *textAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                    [UIColor blackColor],NSForegroundColorAttributeName,
                                    [UIColor blackColor],NSBackgroundColorAttributeName,nil];
    self.navigationController.navigationBar.titleTextAttributes = textAttributes;



    NSError *error = nil;
    if (![[self fetchedResultsController]performFetch:&error]){
        NSLog(@"Error %@",error);
        abort();
    }
    self.searchResults = [NSMutableArray arrayWithCapacity:[[self.fetchedResultsController fetchedObjects] count]];
    [self.tableView reloadData];
}
-(void) viewWillAppear:(BOOL)animated{
    [self.tableView reloadData];
}
- (void)viewDidUnload
{
    self.searchResults = nil;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

    if ([[segue identifier]isEqualToString:@"addToDoItem"]){
        UINavigationController *navigationController = segue.destinationViewController;

        AddToDoItemViewController *addToDoItemViewController = (AddToDoItemViewController*)navigationController.topViewController;
        ToDoItem *addToDoItem = [NSEntityDescription insertNewObjectForEntityForName:@"ToDoItem" inManagedObjectContext:self.managedObjectContext];
        addToDoItem.todoDueDate = [NSDate date];
        addToDoItemViewController.addToDoItem = addToDoItem;
    }
    if ([[segue identifier] isEqualToString:@"toToDoSubItems"]){

        ToDoSubItemsTableViewController *todoSubItemsTableViewController = [segue destinationViewController];
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        ToDoItem *selectedToDoItem = (ToDoItem*)[self.fetchedResultsController objectAtIndexPath:indexPath];
        todoSubItemsTableViewController.selectedToDoItem = selectedToDoItem;



    }




}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        return 1;
    }
    else
    {
        return [[self.fetchedResultsController sections]count];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        return [self.searchResults count];
    }
    else {
    id<NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections]objectAtIndex:section];
    return [sectionInfo numberOfObjects];

    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // Configure the cell...

    ToDoItem *toDoItem = nil;



    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        if (cell==nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
            cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;

        }
        NSLog(@"Configuring cell to show search results");
        toDoItem = [self.searchResults objectAtIndex:indexPath.row];
        cell.textLabel.text = toDoItem.todoName;



        NSDate *fechaToDO = toDoItem.todoDueDate;

        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"EEEE, dd MMMM YYYY"];
        NSString *fechaToDo = [dateFormatter stringFromDate:fechaToDO];



        cell.detailTextLabel.text = fechaToDo;

    }
    else
    {


    ToDoItem *todoItem = [self.fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = todoItem.todoName;



    NSDate *fechaToDO = todoItem.todoDueDate;

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"EEEE, dd MMMM YYYY"];
    NSString *fechaToDo = [dateFormatter stringFromDate:fechaToDO];



    cell.detailTextLabel.text = fechaToDo;
    }
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString *header = @"customHeader";

    UITableViewHeaderFooterView *vHeader;

    vHeader = [tableView dequeueReusableHeaderFooterViewWithIdentifier:header];

    if (!vHeader) {
        vHeader = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:header];
        vHeader.textLabel.backgroundColor = [UIColor redColor];
        vHeader.textLabel.textColor = [UIColor whiteColor];

        vHeader.contentView.backgroundColor = [UIColor redColor];
    }

    if (section == 0) {
        vHeader.textLabel.backgroundColor = [UIColor redColor];
        vHeader.textLabel.textColor = [UIColor whiteColor];

        vHeader.contentView.backgroundColor = [UIColor redColor];
    }

    else if (section == 1) {
        vHeader.textLabel.backgroundColor = [UIColor orangeColor];
        vHeader.textLabel.textColor = [UIColor blueColor];

        vHeader.contentView.backgroundColor = [UIColor orangeColor];
    }
    else if (section == 2) {
        vHeader.textLabel.backgroundColor = [UIColor greenColor];
        vHeader.textLabel.textColor = [UIColor whiteColor];

        vHeader.contentView.backgroundColor = [UIColor greenColor];
    }


    vHeader.textLabel.text = [self tableView:tableView titleForHeaderInSection:section];

    return vHeader;
}
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

    if (tableView == self.searchDisplayController.searchResultsTableView){
        NSString *valor = [NSString stringWithFormat:@"S E A R C H   R E S U L T S (%d)",[self.searchResults count]];
        return valor;
    }
    else {


    id <NSFetchedResultsSectionInfo> theSection = [[self.fetchedResultsController sections]objectAtIndex:section];
    NSString *sectionname = [theSection name];

    if ([sectionname isEqualToString:@"0"]){

        NSString *valor = [NSString stringWithFormat:@"O V E R D U E   (%d)", [self.tableView
                                                             numberOfRowsInSection:section]];
        return valor;
    }
    else if ([sectionname isEqualToString:@"1"]){

        NSString *valor = [NSString stringWithFormat:@"T O D A Y   (%d)", [self.tableView
                                           numberOfRowsInSection:section]];
        return valor;
    }
    else if ([sectionname isEqualToString:@"2"]){

        NSString *valor = [NSString stringWithFormat:@"U P C O M I N G   (%d)", [self.tableView
                                                             numberOfRowsInSection:section]];
        return valor;
    }




    if ([[self.fetchedResultsController sections]count]>0){
        id<NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections]objectAtIndex:section];
        return [sectionInfo name];
    }
    else{
        return nil;
    }
    }

}


#pragma mark - Fetched Results Controller Section

-(NSFetchedResultsController*)fetchedResultsController{

    if (_fetchedResultsController != nil){
        return _fetchedResultsController;
    }
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    NSManagedObjectContext *context = self.managedObjectContext;
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"ToDoItem" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"todoDueDate" ascending:YES];
    NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc]initWithKey:@"todoName" ascending:YES];

    NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:sortDescriptor,sortDescriptor1, nil];
    fetchRequest.sortDescriptors = sortDescriptors;
    _fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:@"sectionIdentifier" cacheName:nil];
    _fetchedResultsController.delegate = self;
    return _fetchedResultsController;
}


#pragma mark - Fetched Results Controller Delegates

-(void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
    [self.tableView beginUpdates];
}

-(void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
    [self.tableView endUpdates];

}

-(void) controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath{

    UITableView *tableView = self.tableView;

    switch (type) {
        case NSFetchedResultsChangeInsert:
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
        case NSFetchedResultsChangeDelete:
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
        case NSFetchedResultsChangeUpdate:{

            ToDoItem *changeToDoItem = [self.fetchedResultsController objectAtIndexPath:indexPath];
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            cell.textLabel.text = changeToDoItem.todoName;
            NSDate *fechaToDO = changeToDoItem.todoDueDate;

            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
            [dateFormatter setDateFormat:@"EEEE, dd MMMM YYYY"];
            NSString *fechaToDo = [dateFormatter stringFromDate:fechaToDO];
            cell.detailTextLabel.text = fechaToDo;
        }
            break;
        case NSFetchedResultsChangeMove:
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
    }


}

-(void)controller:(NSFetchedResultsController *)controller didChangeSection:(id<NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type{

    switch (type) {
        case NSFetchedResultsChangeInsert:
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;
        case NSFetchedResultsChangeDelete:
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;
    }

}





/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        NSManagedObjectContext *context = [self managedObjectContext];
        ToDoItem *ToDoItemToDelete = [self.fetchedResultsController objectAtIndexPath:indexPath];
        [context deleteObject:ToDoItemToDelete];


        NSError *error = nil;
        if (![context save:&error]){
            NSLog(@"Error: %@",error);
        }

    }
}



/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a story board-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}

 */
#pragma mark -
#pragma mark Content Filtering

-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
    self.searchResults = [[self.fetchedResultsController fetchedObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        ToDoItem * item = evaluatedObject;
        NSString* name = item.todoName;

        //searchText having length < 3 should not be considered
        if (!!searchText && [searchText length] < 3) {
            return YES;
        }

        if ([scope isEqualToString:@"All"] || [name isEqualToString:scope])  {
            return ([name rangeOfString:searchText].location != NSNotFound);
        }
        return NO; //if nothing matches
    }]];
}
#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString scope:@"All"];
    return YES;
}

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

@end
CoolMonster
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
       ...
        [context deleteObject:ToDoItemToDelete];

  [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

.....
        NSError *error = nil;
        if (![context save:&error]){
            NSLog(@"Error: %@",error);
        }

    }
}

您应该在此方法内删除行。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

在视图中显示搜索结果

来自分类Dev

如何删除在odoo 8中单击“搜索”视图后打开的搜索视图中的“创建:选项”?

来自分类Dev

屏幕-退出Vim后出现奇怪的行为

来自分类Dev

表视图控制器的奇怪行为

来自分类Dev

在搜索栏表视图中删除单元格会使删除操作执行两次

来自分类Dev

jQuery Mobile嵌套列表视图中的奇怪行为

来自分类Dev

删除后的删除视图未从视图中删除项目

来自分类Dev

设置onitemclicklistener以搜索列表视图中显示的活动搜索结果

来自分类Dev

在视图中删除绑定对象时出现“致命错误:索引超出范围”

来自分类Dev

呈现的子视图中的搜索结果移至子视图

来自分类Dev

音频播放器完成后从表视图中删除行

来自分类Dev

从视图中删除Rails Presenter对象分配

来自分类Dev

删除表视图中的所有行

来自分类Dev

插入耳机后出现奇怪的AVMutableComposition行为

来自分类Dev

Django:首次提交后出现奇怪的Formset行为

来自分类Dev

单击鼠标事件后出现奇怪的鼠标行为

来自分类Dev

安装nvidia 361驱动程序后出现奇怪的行为

来自分类Dev

iPad / iOS7:从中呈现“全屏”视图控制器后,“页面”模式视图控制器出现奇怪行为

来自分类Dev

如何延迟搜索结果显示在表格视图中?

来自分类Dev

如何延迟搜索结果显示在表格视图中?

来自分类Dev

从窗口对象中删除属性时的奇怪行为

来自分类Dev

使用OpenGL进行纹理贴图后出现奇怪的结果

来自分类Dev

在列表视图中搜索后如何重新加载项目

来自分类Dev

提交MVC后在同一视图中显示结果

来自分类Dev

奇怪的行为复制对象

来自分类Dev

动态对象的奇怪行为

来自分类Dev

NSMutableArray与表的奇怪行为

来自分类Dev

表边界奇怪的行为

来自分类Dev

在视图中搜索文本

Related 相关文章

  1. 1

    在视图中显示搜索结果

  2. 2

    如何删除在odoo 8中单击“搜索”视图后打开的搜索视图中的“创建:选项”?

  3. 3

    屏幕-退出Vim后出现奇怪的行为

  4. 4

    表视图控制器的奇怪行为

  5. 5

    在搜索栏表视图中删除单元格会使删除操作执行两次

  6. 6

    jQuery Mobile嵌套列表视图中的奇怪行为

  7. 7

    删除后的删除视图未从视图中删除项目

  8. 8

    设置onitemclicklistener以搜索列表视图中显示的活动搜索结果

  9. 9

    在视图中删除绑定对象时出现“致命错误:索引超出范围”

  10. 10

    呈现的子视图中的搜索结果移至子视图

  11. 11

    音频播放器完成后从表视图中删除行

  12. 12

    从视图中删除Rails Presenter对象分配

  13. 13

    删除表视图中的所有行

  14. 14

    插入耳机后出现奇怪的AVMutableComposition行为

  15. 15

    Django:首次提交后出现奇怪的Formset行为

  16. 16

    单击鼠标事件后出现奇怪的鼠标行为

  17. 17

    安装nvidia 361驱动程序后出现奇怪的行为

  18. 18

    iPad / iOS7:从中呈现“全屏”视图控制器后,“页面”模式视图控制器出现奇怪行为

  19. 19

    如何延迟搜索结果显示在表格视图中?

  20. 20

    如何延迟搜索结果显示在表格视图中?

  21. 21

    从窗口对象中删除属性时的奇怪行为

  22. 22

    使用OpenGL进行纹理贴图后出现奇怪的结果

  23. 23

    在列表视图中搜索后如何重新加载项目

  24. 24

    提交MVC后在同一视图中显示结果

  25. 25

    奇怪的行为复制对象

  26. 26

    动态对象的奇怪行为

  27. 27

    NSMutableArray与表的奇怪行为

  28. 28

    表边界奇怪的行为

  29. 29

    在视图中搜索文本

热门标签

归档