Home > Software engineering >  Ads between cells of UITableView which uses Core Data with NSFetchedResultsController
Ads between cells of UITableView which uses Core Data with NSFetchedResultsController

Time:04-25

(I have already referred enter image description here

The image above is used only for representational purposes, and does not show the actual design/data used by the app I am working with.

The normal cells of the UITableView come from a Core Data fetch request via NSFetchedResultsController using fetchController.object(at: indexPath), whereas the ad cells come from a different data source altogether.

  • Since the ads need to be shown in between the actual table view cells, it messes up the indexPath used by NSFetchedResultsController to retrieve the object from Core Data fetch request.
  • Also the user has the option to delete any of the actual cells (non-ad cells) from the UITableView, which can in-turn change the indexPath of the cells.
  • There can be variable number of ads shown in the cells, for now assume it to be a constant c.

Please let me know if there is a way to handle all these edge cases efficiently, preferably without changing the indexPath object used in fetchController.object(at: indexPath).

CodePudding user response:

You can add a flag to your table view cell class, telling if to show an ad or not:

class MyTableViewCell: UITableViewCell {
    var showAd: Bool = false {
        didSet {
            // `adView` here being either an IBOutlet from the XIB,
            // or a programatically created view, depending on how
            // you designed the cell
            adView.isHidden = !showAd
        }
    }
}

With the above in place, what's left is to store an array of randomly generated indices where you want to show the ads, and update the cell accordingly:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = ...
    cell.showAd = adIndices.contains(indexPath.row)
    return cell
}

  • Related