我的 Storyboard 文件中定义了一个 UINavigationController
流程。根 Controller 是当前用户有权访问的用户列表,当被点击时,会推送与被点击的用户的聊天 View 。这部分功能正常,聊天 View Controller 通过它的 segue 被插入堆栈,并加载它应该加载的消息。
当我弹出聊天 View 并选择不同的用户时,就会出现问题,当聊天加载时,它会清空来自其他用户的旧消息,并将其替换为来自当前所选用户的消息。这意味着该 View 与其旧数据一起保留在内存中。我尝试将 NSFetchedResultsController
设置为 nil
并重新加载数据并处理 tableView:numberOfRowsInSection:
方法的特殊情况如果 NSFetchedResultsController
为 nil
,则返回 0
。
有没有办法卸载这个 View 或清除转换到它之间的表数据以防止剩余的 View 数据?
一些我认为可能相关的代码示例:
// 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;
}
}
不幸的是,这并没有解决问题。每次我弹出聊天 Controller 并交换所选用户,再次执行转场时,它都会从前一个 View 中动画化单元格并加载到当前 View 中。我希望(并期望)每次都从头开始。
再次:是否有一种方法可以完全卸载通过 Storyboard(在 UINavigationController
流程中)实例化的 View ,或者有更好的方法在弹出和推送之间重置 TableView 中的数据所述 View Controller ?
编辑 我在代码示例中拼写错误“disappear”并表示歉意,该方法在项目中过去(现在)拼写正确并且正在被调用(已验证)。感谢@dietbacon 发现了这一点。
最佳答案
如果您在 initWithFetchRequest ... cacheName:
上提供了缓存名称,那么您可以通过调用类方法 +(void)deleteCacheWithName:(NSString *)name 来清除它
使用您最初提供的名称。
我还没有尝试过这个想法,但我认为它应该可以在 viewWillAppear
上正常工作:
关于ios - 如何正确清空通过 UIStoryboard 实例化的 UITableView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23839841/