如何在Swift中延迟回叫 [英] How to delay a return call in Swift

查看:30
本文介绍了如何在Swift中延迟回叫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我目前正在开发一个程序,该程序在UITableView中包含书籍列表.如您所知,TableView有两种方法,一种是带有cellForRowAtIndexPath的方法,另一种是我今天要讨论的方法,即numberOfRowsInSection.因此,我遇到的问题是,我要访问数据库以获取数据库中当前存在的书籍数量,以便返回Book stucts数组中需要多少索引.因此,我有两个小组,买和卖,其中可能有也可能没有任何书.

Hello guys I am currently working on a program that holds a list of books in a UITableView. As you know, the TableView takes two methods, one with cellForRowAtIndexPath and the one I will be talking about today, numberOfRowsInSection. So the problem I am having is that I access my database to get the number of books that are currently in the database in order to return how many indices I will need in the array of Book stucts. So I have two groups, buy and sell, that may or may not have any books in them.

无论如何,我填充了数组(开头是空的),然后将books.count返回为numberOfRowsInSection.问题是执行返回后,随着数组的填充,我一直返回0.

Anyway, I populate my array (it's empty to start with) and then I return the books.count as the numberOfRowsInSection. The problem is that I am consistently returning 0 seeing as the array gets populated after the return is executed.

下面是我的代码.

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    populateArray()
    print("books.count: ",books.count)
    return books.count // KEEPS RETURNING 0 BC IT HASN'T POPULATED YET *ARRRRRRGH*
}

func populateArray(){
    print("started looking")
    var indices = 0

    if divider.selectedSegmentIndex == 0{
        ref.child(school).observeEventType(.Value, withBlock: {     (snapshot) in
            let numSelling = snapshot.value!["numSelling"] as! Int // gets numSelling
            if numSelling  > 0 {
                self.noEntries = false
                print("numSelling: ", numSelling) //see console
                indices = numSelling
            }else{
                self.noEntries = true
                indices = 1
                print("No Values Selling")
            }
        }) { (error) in
            print(error.localizedDescription)
        }
    }else{
        ref.child(school).observeEventType(.Value, withBlock: {     (snapshot) in
            let numBuying = snapshot.value!["numBuying"] as! Int // gets numBuying
            if numBuying  > 0 {
                self.noEntries = false
                print("numBuying: ", numBuying) //see console
                indices = numBuying
            }else{
                self.noEntries = true
                indices = 1
            }
        }) { (error) in
            print(error.localizedDescription)
        }
    }



    delay(0.5){
        print("ind: ", indices) // printing correctly
        if(self.noEntries){ // just add one book to get the indices to be 1
            self.books.append(Book(isbn: "", title: "", author: "", edition: "", price: "", uid: ""))

            return
        }
        if self.divider.selectedSegmentIndex == 0{
            self.ref.child(self.school).child("selling").observeEventType(.Value, withBlock: {    (snapshot) in
                let booksJSON = snapshot.value! as! NSArray

                for bookJSON in booksJSON { // add the book to the array
                    let tempAuthor = bookJSON["authors"] as! String
                    let tempTitle = bookJSON["title"] as! String
                    let tempEdition = bookJSON["edition"] as! String
                    let tempPrice = bookJSON["price"] as! String
                    let tempISBN = bookJSON["isbn"] as! String
                    let tempUID = bookJSON["uid"] as! String
                    self.books.append(Book(isbn: tempISBN, title: tempTitle, author: tempAuthor, edition: tempEdition, price: tempPrice, uid: tempUID))
                }

            }) { (error) in
                print(error.localizedDescription)
            }
        }else if self.divider.selectedSegmentIndex == 1{
            self.ref.child(self.school).child("buying").observeEventType(.Value, withBlock: {    (snapshot) in
                let booksJSON = snapshot.value! as! NSArray

                for bookJSON in booksJSON { // add the book to the array
                    let tempAuthor = bookJSON["authors"] as! String
                    let tempTitle = bookJSON["title"] as! String
                    let tempEdition = bookJSON["edition"] as! String
                    let tempPrice = bookJSON["price"] as! String
                    let tempISBN = bookJSON["isbn"] as! String
                    let tempUID = bookJSON["uid"] as! String
                    self.books.append(Book(isbn: tempISBN, title: tempTitle, author: tempAuthor, edition: tempEdition, price: tempPrice, uid: tempUID))
                }

            }) { (error) in
                print(error.localizedDescription)
            }
        }
    }

}

func delay(delay:Double, closure:()->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(), closure)
}

请记住,我无法在此方法中进行回调,因为在加载视图时程序会自动调用它.

Keep in mind that I cannot make a callback in this method because it is automatically called by the program when the view is loaded.

此外,延迟段也在努力阻止同一件事的发生.问题是我不能将延迟放在返回值周围,因为它认为我想为延迟块返回一个Int.

Also, the delay segments are in efforts to stop the same thing from happening. Problem is that I cannot put the delay around the return because it thinks I want to return an Int for the delay block.

控制台:

started looking
books.count:  0
started looking
books.count:  0
started looking
books.count:  0
started looking
books.count:  0
numSelling:  6
numSelling:  6
numSelling:  6
numSelling:  6
ind:  6
ind:  6
ind:  6
ind:  6

您可以看到它甚至在从数据库到达numSelling值之前就返回0.

As you can see it is returning 0 before it even gets to the numSelling value from the database.

非常感谢您的帮助,祝您生活愉快!

Thank you so much for your help and have a great day!

推荐答案

一旦调用了某个方法,就不能延迟返回该方法,但是您可以要求表视图再次调用数据源方法.

You cannot delay returning to a method once it has been called, but you can ask the table view to call the data source methods again.

最简单的解决方案是在数据填充后(即,在 populateArray()方法的末尾)在表视图上调用 reloadData().我可能还会将调用移到其他地方的 populateArray()(如果合适的话,也许是 viewDidLoad()).

The easiest solution would be to call reloadData() on your table view once your data has been populated (i.e., at the end of your populateArray() method). I would probably also move the call to populateArray() somewhere else (perhaps viewDidLoad(), if that's appropriate).

这篇关于如何在Swift中延迟回叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆