我的情节提要文件中定义了UINavigationController流。根控制器是当前用户有权访问的用户列表,当其被点击时,该列表会推送与被点击的用户的聊天视图。该部分功能正常,聊天视图控制器通过其segue推送到堆栈上,并加载应加载的消息。

当我弹出聊天视图并选择其他用户时,会出现问题,当聊天加载时,它会清空其他用户的旧消息,并用当前所选用户的消息替换它们。这意味着该视图将其旧数据保留在内存中。我尝试设置将其备份到NSFetchedResultsControllernil并重新加载数据,并处理tableView:numberOfRowsInSection:如果0NSFetchedResultsControllernil方法的特殊情况。

有没有一种方法可以卸载此视图或在过渡到表视图之间清除表数据以防止剩余视图数据?

我认为一些相关的代码示例:

// View controller that loads the chat view
// Not the view with leftover data
- (void)collectionView:(UICollectionView *) didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    self.selectedUser = [[self.fetchedResultsController fetchedObjects] objectAtIndex:indexPath.item];
    [self performSegueWithIdentifier:@"userListToChatView" sender:self];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"userListToChatView"]) {
        ChatViewController *ctrl = [segue destinationViewController];
        ctrl.recipient = self.selectedUser;
        self.selectedUser = nil;
    }
}


在ChatViewController中:

@interface ChatViewController ()

@property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;

@end

@implementation ChatViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [RequestConnection fetchMessagesForUser:[SessionManager currentUser]];
    [self.fetchedResultsController performFetch:nil];
}

// Standard table view data source methods, fetching cell information for index
// paths and returning the number of items in the fetched results controller

- (NSFetchedResultsController *)fetchedResultsController {
    if (!_fetchedResultsController) {
        // Create Fetch Request, Sort Descriptors and Fetched Results Controller
    }

    return _fetchedResultsController;
}

@end


我试过实现这样的viewDidDisappear方法:

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];

    _fetchedResultsController.delegate = nil;
    _fetchedResultsController = nil;

    [self.tableView reloadData];
}

// And modified the numberOfRowsInSection
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_fetchedResultsController) {
        return [[self.fetchedResultsController fetchedObjects] count];
    } else {
        return 0;
    }
}


不幸的是,哪一个都没有解决问题。每次我弹出聊天控制器并交换选定的用户时,再次进行搜索,它都会使上一个视图中的单元格动画化并加载当前视图。我希望(并期望它)每次都从一个干净的开始。

再说一次:是否有一种方法可以完全卸载通过Storyboard实例化的视图(在UINavigationController流中),或者是一种更好的方法,用于在该视图控制器的pop和push之间重置表视图中的数据?

编辑我在代码示例中拼写错误“消失”并道歉,该方法在项目中正确(正确地)被拼写,并且被调用(验证)。感谢@dietbacon赶上了。

最佳答案

如果在initWithFetchRequest ... cacheName:上提供了缓存名称,则可以通过使用最初提供的名称调用类方法+(void)deleteCacheWithName:(NSString *)name来清除它。

我没有尝试过这个想法,但是我认为它在viewWillAppear上应该可以正常工作:

关于ios - 如何正确清空通过UIStoryboard实例化的UITableView?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23839841/

10-14 23:10
查看更多