Problems updating Uicollectionview

Asked

Viewed 89 times

2

I’m having trouble giving reloadData() in Uicollectionview when using the UISearchBar. Debugging to see if the object coming from REALM was nil I realized that the function to filter is coming with the correct values. Put when giving reloadData() in Collection nothing happens....

Class of the Uicollectionview

 class HomeViewController: UIViewController,UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UISearchBarDelegate {

//MARK: - IBOutlet
@IBOutlet weak var searchbar: UISearchBar!

@IBOutlet weak var ListOfMovies: UICollectionView!

//MARK: - Variables
var movies : Results<Moviess>!

var indexPath: IndexPath!
let realm = try! Realm()

override func viewDidLoad() {
    super.viewDidLoad()
    ListOfMovies.delegate = self
    ListOfMovies.dataSource = self
    searchbar.delegate = self
    getRequest()

}

override func viewWillAppear(_ animated: Bool) {
    getObjects()
}
func getObjects() -> Results<Moviess>{
    movies = realm.objects(Moviess.self)
    return movies
}

func getRequest(){
    if getObjects().count < 1 {
        RequestData.requisicao { (result) in
               switch(result){
                case .success(let detalhe):
                    self.ListOfMovies.reloadData()
                    print(detalhe)
                case .failure(let error):
                   print(error)
               }
           }
    }}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    print( getObjects().count,"<---  Items")
    return getObjects().count
  }

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listOfMovies", for: indexPath) as! HomeCollectionViewCell

    let infos = getObjects()[indexPath.item]
    cell.configurationMovie(movie: infos)
    return cell
  }
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let infos = getObjects()[indexPath.item]
    infos.togleFavorite()
    ListOfMovies.reloadData()
    print(infos.title)
}


  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
      return UIDevice.current.userInterfaceIdiom == .phone ? CGSize(width: collectionView.bounds.width/2-20, height: 200) : CGSize(width: collectionView.bounds.width/3-20, height: 250)
  }

  func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    print(searchText)
    if !searchText.isEmpty{

        movies = getObjects().filter("title CONTAINS[cd] %@", searchText)
        print(movies.count, "<----- item FIltred")
        self.ListOfMovies.reloadData()
    }
}

}

When I type something in Archbar I see this

20 <---  Items
 A
10 <----- item FIltred. <-- Aqui é onde ele filtra o resultados
20 <---  Items <--- Apos o reloadData() da collection ele volta com os itens iniciais 

Object class REALM

import RealmSwift
import UIKit

class Moviess: Object{
 @objc dynamic var id = 0
 @objc dynamic var title = ""
 @objc dynamic var overview = ""
 @objc dynamic var poster = ""
 @objc dynamic var isFavorites = false

 override class func primaryKey() -> String? {
    return "id"
 }
 convenience init (id: Int){
    self.init()
    self.id = id
 }

 override class func indexedProperties() -> [String] {
    return ["isFavorites"]
 }

 func insertMovieData(list: Moviess){
    do {
        let realm = try! Realm()
        try! realm.write({ () -> Void in
            realm.add(list)
        })
    } catch let error as NSError{
        print("insert error : \(error)")
    }
 }

 func togleFavorite(){
    try? realm?.write{
        isFavorites = !isFavorites
    }
  }
}

Where can I be wrong? Thank you!

1 answer

0


Within the function numberOfItemsInSection you are calling getObjects(), she is "resetting" the values of movies for all the objects you have in the Realm:

func getObjects() -> Results<Moviess>{
    movies = realm.objects(Moviess.self)
    return movies
}

And your table is filled with this variable. When you call the reloadData(), one of the functions performed from the datasource of the tableView is the numberOfItemsInSection:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    print( getObjects().count,"<---  Items")
    return getObjects().count
  }

Basically you are filtering the data, and when you are going to update the table, you are doing fetch of all the data again.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.