How can I properly reload data from my UICollectionView?

advertisements

I have a function that is called in the viewDidLoad of my collectionView that loads content from my server into the view:

// Load Books Class
    func loadBooks() {

        var query = PFQuery(className: "Books")
        query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
            if error == nil {
                let bookObjects = objects as! [PFObject]
                for (index, object) in enumerate(bookObjects) {
                    self.books.append(Book(pfBook: object))
                }
            }else if let secondMessage = error?.userInfo?["error"] as? String
                where secondMessage == "The Internet connection appears to be offline." {
                    self.failedMessage(secondMessage)
            }
            dispatch_async(dispatch_get_main_queue()){

            self.collectionView!.reloadData()

            }
        }
    }

And here is my function that is called when the collectionView is refreshed, I basically am attempting to just reload the items back to the view:

func startRefresh(){

        dispatch_async(dispatch_get_main_queue()) {
            self.loadBooks()

            println("loading complete!")

            self.refreshControl.endRefreshing()
        }

    }

However when I refresh, rather than loading the same content again, it loads twice the amount of content.. sort of like calling the load method on top of the load method, rather than re-executing it.. looking at my logic, what should I do to fix the issue?


You need to clear your array before you start adding items. Add self.books.removeAll() to your code, like following:

func loadBooks() {

    var query = PFQuery(className: "Books")
    query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
        if error == nil {
            self.books.removeAll()
            let bookObjects = objects as! [PFObject]
            for (index, object) in enumerate(bookObjects) {
                self.books.append(Book(pfBook: object))
            }
        }else if let secondMessage = error?.userInfo?["error"] as? String
            where secondMessage == "The Internet connection appears to be offline." {
                self.failedMessage(secondMessage)
        }
        self.collectionView!.reloadData()
    }
}

Edit: Since Parse callbacks are executed on main thread, you don't need the dispatch_async part of your code.