如果另一个功能完成,我该如何调用函数? (Swift并从Parse中检索)

时间:2015-12-13 15:30:02

标签: swift function parse-platform pfquery pfquerytableviewcontrolle

如果我在单独的函数中从Parse后端检索到某个PFObject,我只想调用 函数。目前我在设置3.0的延迟后调用第二个函数并且它正在工作,但只有在3.0内调用第一个查询函数时才会调用,否则我必须pullToRefresh第一个函数最终完成后,tableView填充Parse数据。 (顺便说一下,我使用的是PFQueryTableViewController

这是我目前的代码(我知道queryForTable是一个覆盖所以无论如何被调用,所以有没有办法将其更改为普通的func?):

override func viewDidLoad() {

    // ideally want something like "if getX'IsComplete' then queryForTable() and self.loadObjects()"

    retrieveFirstX()

    let delay = 3.0 * Double(NSEC_PER_SEC) // retrieveFirstX must load within 3.0 for table to populate without needing to pullToRefresh
    let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
    dispatch_after(time, dispatch_get_main_queue(), {

        self.queryForTable()
        self.loadObjects()
    })
}

var X = PFObject(className: "X")

func retrieveFirstX() -> Bool {

    let xQuery = PFQuery(className: "X")
    xQuery.orderByDescending("createdAt")
    xQuery.getFirstObjectInBackgroundWithBlock {
        (object: PFObject?, error: NSError?) -> Void in
        if error == nil {

            self.X = object!
        }
    }
    return true
}

 override func queryForTable() -> PFQuery {

    let xRelation = X.relationForKey("xPosts") as PFRelation!
    let relationQuery = xRelation.query()

    let xPostsQuery = PFQuery(className: "Posts")
    xPostsQuery.includeKey("postUser")
    xPostsQuery.whereKey("objectId", matchesKey: "objectId", inQuery: relationQuery)
    xPostsQuery.cachePolicy = .NetworkElseCache
    xPostsQuery.orderByDescending("createdAt")
    return xPostsQuery
}

我是否需要使用完成处理程序,如果是,我该如何操作,因为我以前从未使用过它们?

提前致谢!

1 个答案:

答案 0 :(得分:3)

完成处理程序听起来很正确,例如:

override func viewDidLoad() {
    let completionHandler = {
        self.queryForTable()
        self.loadObjects()
    }
    retrieveFirstX(completionHandler)
}

func retrieveFirstX(completion: ()->()) -> Bool {
    let xQuery = PFQuery(className: "X")
    xQuery.orderByDescending("createdAt")
    xQuery.getFirstObjectInBackgroundWithBlock {
        (object: PFObject?, error: NSError?) -> Void in
        if error == nil {
            self.X = object!
            completion()
        }
    }
    return true
}