0

I'm trying to filter a list of users in a TableViewDiffableDataSource. The filtered array of users is passed to the following function:

private func updateUserCell(_ users: Users? = nil) {

        guard let newUsers = users else {

            print("No users to show")

            return

        }

        snapShot.deleteItems(viewModel.userList)

        dataSource!.apply(snapShot, animatingDifferences: false)

        if newUsers == [] { return }

        var snapShot = dataSource?.snapshot()

        snapShot?.appendItems(newUsers, toSection: .main)

        dataSource!.apply(snapShot!, animatingDifferences: true)

    }

Debugging shows that the users get appended correctly in the snapshot. But applying shows correct number of filtered users but only the users from the top of the complete list.

i.e. if I have a full list of users [Chloe, Max, John, Martin]. Searching for "jo" only shows Chloe. Searching for "ma" shows Chloe and Max instead of Max and Martin.

PhoenixDev
  • 746
  • 2
  • 9
  • 22
  • is the `vm.userlist` the full list of all users? So your approach is to delete all users from a snapshot (where does this snapshot come from?), apply it, create a new snapshot (which you want to be empty?), append the users you want to it, and then apply that snapshot? – flanker Feb 08 '22 at 17:45

1 Answers1

0

I'm not sure I fully understand the logic behind your approach above but unless I'm missing something that the snippet isn't making clear, a far simpler approach would appear to be just to create a new snapshot with the required users and apply that, rather than modifying the existing one.

private func updateUserCell(_ users: Users? = nil) {
  guard let newUsers = users, !newUsers.isEmpty else {return}

  var snapshot = NSDiffableDataSourceSnapshot<Section, User>()
  snapshot.appendSections([.main])
  snapshot.appendItems(newUsers, toSection: .main)
  dataSource.apply(snapshot, animatingDifferences: true)
}

nb. having an update users method that default to nil and therefore bailing out seems a strange design choice. It suggests the logic behind calling it is a bit skewed.

flanker
  • 3,840
  • 1
  • 12
  • 20