将多个查询结果添加到数组

时间:2016-10-18 00:46:44

标签: ios swift parse-platform

我正在尝试从我的解析数据库运行4个查询,每个查询只拉动1个对象。我试图将每个对象添加到一个数组,然后可以在集合视图中使用。查询成功运行但应用程序崩溃,因为它正在拉空值。这是我的代码:

var query1desc = ""
var query2desc = ""
var descs = [String]()

fileprivate func fetchUsers() {

        let query1 = PFQuery(className: "Messages")
        query1.limit = 1
        query1.findObjectsInBackground{
            (objects, error) -> Void in
            if error == nil {
                if objects?.count == 0 {
                 } else {
                    let object = objects![0] as! PFObject
                    self.query1desc = object["message"] as! String
                }

            }
        }
            let query2 = PFQuery(className: "Messages")
            query2.limit = 1
            query2.findObjectsInBackground{
                (objects, error) -> Void in
                if error == nil {
                    if objects?.count == 0 {
                       } else {
                       let object = objects![0] as! PFObject
                       self.query2desc = object["message"] as! String
                    }
                 }
            }

self.descs = [self.query1desc, self.query2desc]
self.collectionView.reloadData()

有没有人知道修复此问题的方法,以便self.descs不仅提供nil值?当我在查询本身内打印时,我知道正在拉动对象。提前谢谢。

1 个答案:

答案 0 :(得分:0)

我认为desc变量保持nil值,因为您的程序正在执行数组赋值代码部分,而完成处理程序仍在处理查询请求。您需要等待所有查询请求完成,然后才能收集所有结果。

let workGroup = DispatchGroup()

let queueForQuery1 = DispatchQueue(label: "firstQuery")
let query1 = PFQuery(className: "Messages")
query1.limit = 1

workGroup.enter()

queueForQuery1.async(group:workGroup) { 

    query1.findObjectsInBackground{ (objects, error) -> Void in

        if error == nil {
            if objects?.count == 0 {
            } else {
                let object = objects![0] as! PFObject
                self.query1desc = object["message"] as! String
             }
       }
       workGroup.leave()
    }
}

let queueForQuery2 = DispatchQueue(label: "secondQuery")
let query2 = PFQuery(className: "Messages")
query2.limit = 1

workGroup.enter()


queueForQuery2.async(group:workGroup) { 

    query2.findObjectsInBackground{ (objects, error) -> Void in

        if error == nil {
            if objects?.count == 0 {
            } else {
                let object = objects![0] as! PFObject
                self.query1desc = object["message"] as! String
             }
       }
       workGroup.leave()
    }
}

workGroup.notify(queue: DispatchQueue.main){
    self.descs = [self.query1desc, self.query2desc]
    self.collectionView.reloadData()
}