Kako ažurirati kolekcije podataka u iOS aplikacijama?
sobes.tech АИ
Одговор од АИ
Postoji nekoliko načina za ažuriranje kolekcija podataka u iOS:
-
reloadData(): Najjednostavniji, ali i najmanje efikasan način. U potpunosti ponovo učitava sve podatke.tableView.reloadData() -
beginUpdates()/endUpdates(): Omogućava izvođenje paketnih promena (ubacivanje, brisanje, ažuriranje redova/sekcija) sa animacijom. Zahteva ručno upravljanje indeksima.tableView.beginUpdates() tableView.insertRows(at: [IndexPath(row: newData.count - 1, section: 0)], with: .automatic) tableView.endUpdates() -
performBatchUpdates(_:completion:): Modernija i preferirana zamena zabeginUpdates()/endUpdates(). Takođe vrši paketne promene sa animacijom.collectionView.performBatchUpdates({ collectionView.insertItems(at: [IndexPath(item: newData.count - 1, section: 0)]) }, completion: nil) -
diffable data sources: Od iOS 13,UICollectionViewDiffableDataSourceiUITableViewDiffableDataSourcepružaju deklarativni način upravljanja podacima. Razlike između stare i nove verzije podataka automatski se izračunavaju pomoćuDiffing.struct MySection: Hashable { let id = UUID() } struct MyItem: Hashable { let id = UUID() let title: String } var dataSource: UICollectionViewDiffableDataSource<MySection, MyItem>! // ... var snapshot = NSDiffableDataSourceSnapshot<MySection, MyItem>() snapshot.appendSections([MySection()]) snapshot.appendItems([MyItem(title: "New Item")]) dataSource.apply(snapshot, animated: true) -
Core Data fetched results controller: Za rad sa Core Data,
NSFetchedResultsControllerautomatski prati promene i obaveštava delegata o potrebi za ažuriranjem UI.// U delegatu NSFetchedResultsController - (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedObjectChangeType)type newIndexPath:(NSIndexPath *)newIndexPath { switch(type) { case NSFetchedResultsChangeInsert: [self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; break; // ... ostali tipovi NSFetchedObjectChangeType } }
Izbor metode zavisi od složenosti ažuriranja, potrebe za animacijom i korišćene arhitekture (npr. Core Data). Diffable data sources su najpreporučljiviji pristup za nove projekte.