函数返回值太快

时间:2016-05-01 20:36:21

标签: ios cloudkit

我在项目中使用CloudKit并且我正在从云中加载数据以检查用户是否已经在云中,但是当我调用loadUser()函数时,代码已经返回在实际值出现之前的值!这是代码:

override func viewDidLoad() {
    super.viewDidLoad()

    var shouldSaveUser = Bool()
    shouldSaveUser = loadUser()

    if shouldSaveUser == true {
        send2Cloud()
    } else {
        print("\nUSER ALREADY IN THE CLOUD\n")
    }
}

func loadUser() -> Bool {

    users = [CKRecord]()

    let publicData = CKContainer.defaultContainer().publicCloudDatabase
    let predicate = NSPredicate(format: "id == %@", id)
    let query = CKQuery(recordType: "User", predicate: predicate)

    publicData.performQuery(query, inZoneWithID: nil) { (results: [CKRecord]?, error: NSError?) -> Void in

        publicData.performQuery(query, inZoneWithID: nil) {
            records, error in
            if error != nil {
                print(error?.localizedDescription)
            }
        }

        if let users = results {
            self.users = users
            print("\nHow many users: \(self.users.count)\n")

            if self.users.count != 0 {
                self.aux = false
            } else {
                self.aux = true
            }
            print("\n\(self.aux)")
        }
    }
    print("\n\(self.aux)")
    return self.aux
}

现在,我有0个用户,因此self.aux应该等于true,这只有在loadUser()返回错误值后才会发生!这是控制台中显示的顺序:

false
USER ALREADY IN THE CLOUD
How many users: 0
true

它应该是true但是到true更改已经太晚了! 有谁知道如何解决这个问题?任何帮助非常感谢!!谢谢,伙计们!

1 个答案:

答案 0 :(得分:-1)

您的代码似乎在后台线程中运行publicData.performQuery,并在完成后调用

  if error != nil {
     print(error?.localizedDescription)
                  }

因此,在返回结果之前,块之外的publicData.performQuery之后的代码会运行。因此,您应该将依赖于此查询的代码放在if error != nil { //CODE HERE }