如何正确重新加载我的UICollectionView数据?

时间:2015-09-08 09:33:10

标签: ios xcode swift uicollectionview reload

我有一个在我的collectionView的viewDidLoad中调用的函数,它将我服务器中的内容加载到视图中:

// 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()

            }
        }
    }

这是我刷新collectionView时调用的函数,我基本上只是尝试将项目重新加载回视图:

func startRefresh(){

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

            println("loading complete!")

            self.refreshControl.endRefreshing()
        }

    }

然而,当我刷新,而不是再次加载相同的内容时,它加载了两倍的内容量。有点像在load方法之上调用load方法,而不是重新执行它..看着我逻辑,我该怎么做才能解决问题?

2 个答案:

答案 0 :(得分:2)

在开始添加项目之前,您需要清除阵列。将self.books.removeAll()添加到您的代码中,如下所示:

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()
    }
}

编辑:由于Parse回调是executed on main thread,因此您不需要代码的dispatch_async部分。

答案 1 :(得分:1)

您应该移除self.books的所有子女 self.books.removeAll()之前的self.books.append(Book(pfBook: object))