概要:
次のiOSプロジェクトがあります。
- コア データ (を使用
NSFetchedResultsController
) - データを表形式で表示 (
UITableView
)
私がしたいこと:
- ユーザーがレコードを追加すると、新しく追加されたレコードまでスクロールしたい。
私がやった事
- 新しいレコードが追加されると、メソッド内で、タイプが挿入/更新/移動の場合、
NSFetchedResultsControllerDelegate
インデックス パスをプロパティに保存します。lastAddedIndexPath
- 保存を呼び出した後、「lastAddedIndexPath」までスクロールします
コード (NSFetchedResultsControllerDelegate)
- (void)controller:(NSFetchedResultsController *)controller
didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath
forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
if (!self.suspendAutomaticTrackingOfChangesInManagedObjectContext)
{
switch(type)
{
case NSFetchedResultsChangeInsert:
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
NSLog(@"going to store insert - scroll");
self.lastAddedIndexPath = newIndexPath;
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
NSLog(@"going to store update - scroll");
self.lastAddedIndexPath = newIndexPath;
break;
case NSFetchedResultsChangeMove:
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
NSLog(@"going to store move - scroll");
self.lastAddedIndexPath = newIndexPath;
break;
}
}
}
スクロールするコード
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
if (self.beganUpdates) //already [self.tableView beginUpdates] invoked
{
[self scrollToLastAddedIndexPath]; //contains the logic to scroll
[self.tableView endUpdates];
}
}
問題
- レコードは、別のスレッドで非同期にテーブル ビューに追加されていると思います。
- そのため、データベースを保存した後でも
lastAddedIndexPath
、テーブル内のレコードまでスクロールすると、まだ存在しません。
質問
- レコードがテーブル ビューに追加された後、新しく追加されたレコード パスにスクロールするにはどうすればよいですか?
- データベースがいつ保存されたかを知るために通知を使用する必要がありますか?
- 他の代替アプローチはありますか?