title: Tableview category refinement
body: <p>I have a large amount of data in firebase that I am displaying on a tableview. The data is of different businesses nearby and I want to add a feature to filter/sort the data by business type(food, travel, shopping, ect..). I added a tab bar with a segmented control to work as the filter/sort feature. When the user selects shopping I want only the shopping business to display and all of the other business to delete. I have tried a few different ways to do this but not have worked successfully. I am able to populate the tableview cells correctly when the app first loads but I cannot correctly load the cells when a filter/sort option is selected. Here is my current code.</p>
  
  <pre><code>@IBOutlet weak var selects: UISegmentedControl!
  @IBAction func selections(_ sender: Any) {
      if selects.selectedSegmentIndex == 0 {
          //all
          print("all")
          cate = 0
          loadposts()
      }
      else if selects.selectedSegmentIndex == 1 {
          //shopping
          print("shopping")
          cate = 1
          loadposts()
      }
      else if selects.selectedSegmentIndex == 2 {
          //food
          print("food")
          cate = 2
          loadposts()
      }
      else if selects.selectedSegmentIndex == 3 {
          //travel
          print("travel")
          cate = 3
          loadposts()
      }
      else if selects.selectedSegmentIndex == 4 {
          //events
          print("event")
          cate = 4
          loadposts()
      }
      else {
          //more
          print("more")
          cate = 5
          loadposts()
      }
  }
  
  func loadposts() {
      ref = Database.database().reference()
      let trace = Performance.startTrace(name: "test trace")
      trace?.incrementCounter(named:"retry")
      let userID = Auth.auth().currentUser?.uid
      print(userID!)
  
  
     ref.child("Users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
          // Get user value
          let value = snapshot.value as? NSDictionary
          let one1 = value?["Coupon Book"] as? String ?? ""
          let two2 = value?["charitylogo"] as? String ?? ""
          print("one1: \(one1)")
          bogus.set(one1, forKey: "bogus")
      let url = URL(string: two2)
      print("Url: \(url!)")
      URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
          if error != nil{
              print(error)
              return
          }
          DispatchQueue.main.async {
             /// self.centernavlogo = UIButton(type: .custom)
              let pim = UIImage(data: data!)
              self.vood.background = pim
              ///self.centernavlogo.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
             /// self.centernavlogo.imageView?.contentMode = .scaleAspectFit
             /// self.centernavlogo.setImage(pim, for: .normal)
            ///  self.centernavlogo.setBackgroundImage(pim, for: .normal)
  
              /// self.centernavlogo.tintColor = UIColor.white
  
              ///self.centernavlogo.setBackgroundImage(pim, for: .normal)
  
  
          }
  
      }).resume()
  
      Database.database().reference().child("Coupons").child(one1).observe(.childAdded) { (Snapshot : DataSnapshot) in
          if let dict = Snapshot.value as? [String: Any] {
              let captiontext = dict["company name"] as! String
              let offerx = dict["totaloffer"] as! String
              let logocomp = dict["logo"] as! String
              let actchild = dict["childx"] as! String
              let categ = dict["category"] as! String
              let post = Post(captiontext: captiontext, PhotUrlString: actchild, offertext: offerx, actualphoto: logocomp, cat2: categ)
              self.posts.append(post)
              self.tableview.reloadData()
  
              print(self.posts)
          }
      }
      }) { (error) in
          print(error.localizedDescription)
      }
      trace?.stop()
  }
  
  override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
      // Dispose of any resources that can be recreated.
  
  }
  func delay(_ delay:Double, closure:@escaping ()-&gt;()) {
      let when = DispatchTime.now() + delay
      DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
  }
  
  }
  extension ViewController : UITableViewDataSource {
  
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {
  
      let cell = tableview.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as! prot
  
      if cate == 0{
          ///home
          if posts[indexPath.row].cat1 == "" {
  
          }else{
  
          }
      }else
      if cate == 1{
      ///shopping
      if posts[indexPath.row].cat1 == "shopping" {
  
      }
  }else
      if cate == 2{
      ///food
      if posts[indexPath.row].cat1 == "food" {
  
      }
  }else
      if cate == 3{
      ///travel
      if posts[indexPath.row].cat1 == "travel" {
  
      }
  }else
      if cate == 4{
      ///event
      if posts[indexPath.row].cat1 == "event" {
  
      }
  }else
      if cate == 5{
      ///more
      if posts[indexPath.row].cat1 == "more" {
              posts.remove(at: indexPath.item)
  
          DispatchQueue.main.async {
  tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.none)
          }
             print("category 5 running")
          }
          tableView.reloadData()
      }
      if cate == 6{
          ///gps
      }
  
      cell.cllimg?.image = nil
      cell.maintxt.text = nil
      cell.sidetxt.text = nil
      cell.maintxt.text = posts[indexPath.row].caption
      cell.sidetxt.text = "Offers: \(posts[indexPath.row].offercount)"
  
  
  
      let hone = posts[indexPath.row]
      if let maria = hone.actphot {
          let url = URL(string: maria)
          URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
              if error != nil{
                  print(error)
                  return
              }
              cell.cllimg?.contentMode = .scaleAspectFit
              DispatchQueue.main.async {
  
              cell.cllimg?.image = UIImage(data: data!)
              }
  
          }).resume()
      }
  
      return cell
  }
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {
      return posts.count
  }
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  
      passinfo.set("\(posts[indexPath.row].photourl)", forKey: "passinfo")
      self.performSegue(withIdentifier: "yourSegue", sender: self)
  }
  
  
  
  }
  </code></pre>
  
  <p>With the code above code, the table is blank when a category is selected</p>
  
  <pre><code>if cate == 5{
      ///more
      if posts[indexPath.row].cat1 == "more" {
          tableView.beginUpdates()
              posts.remove(at: indexPath.item)
              tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.none)
             print("category 5 running")
          }
          tableView.endUpdates()
      }
  </code></pre>
  
  <p>With the code above, the app crashes and gives me this error.</p>
  
  <blockquote>
    <p>Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (14) must be equal to the number of rows contained in that section before the update (15), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'</p>
  </blockquote>
  
  <p>I have also tried removing <code>posts.remove(at: indexPath.item)</code> and <code>tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.none)</code> but neither worked. </p>