PFUser 查询最初不更改变量 运行

PFUser Query doesn't change variable at first run

我有一个文本字段,用户可以在其中输入另一个用户的用户名,以将他添加为朋友。我正在使用 PFQuery 查询所有用户,然后检查在文本字段中键入的用户名是否存在。如果它存在,则会出现一个按钮(我知道我在文本中不小心称它为标签),如果用户按下按钮,则应添加其他用户。我的查询有问题,当我搜索一个用户(我知道这个用户存在)时,它不会在第一个 运行 时打印用户名,只有当我再次 运行 时才打印。似乎它只在第二次更改值。

import UIKit
import Parse
import Bolts

var userToAdd = [String]()

class AddFriendViewController: UIViewController {

@IBOutlet var addFriendLabel: UIButton!
@IBOutlet var searchUserTF: UITextField!
override func viewDidLoad() {
    super.viewDidLoad()
    addFriendLabel.setTitle("", forState: .Normal)
    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func checkForUser() {

    if searchUserTF.text != "" {

        var username = searchUserTF.text            
        var query = PFUser.query()
        query?.findObjectsInBackgroundWithBlock({ (objects:[PFObject]?, error:NSError?) -> Void in

            for object in objects!{
            let recievedUser = (object as PFObject)["username"] as! String

                if recievedUser == username{
                    userToAdd.removeAll()
                    userToAdd.append(username!)

                    self.addFriendLabel.setTitle("Share myEvents with \(userToAdd[0])", forState: .Normal)
                }              
            } 
        })

    }  
}

@IBAction func searchButtonPressed(sender: AnyObject) {

    checkForUser()
    print(userToAdd)
    if addFriendLabel.hidden == true{

        let alertController = UIAlertController(title: "Username not found!", message: "A user with this username does not exist, please check the spelling or your internet connection", preferredStyle: .Alert)
        let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
        alertController.addAction(action)
        self.presentViewController(alertController, animated: true, completion: nil)

    } 
}

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

print(userToAdd) 只显示我 ["Test"] 当我再次点击按钮时,我第一次点击它时,它显示我 []。我知道我也可以将它保存为字符串而不是数组,我只是在玩,因为使用字符串我遇到了完全相同的问题。

我希望有人明白我的意思 :D 并且知道我的问题的解决方案。

正如函数名称 findObjectsInBackgroundWithBlock 所暗示的那样,查询操作在后台完成,因此在调用 checkForUser() 后立即尝试访问 userToAdd 将得到 nil,因为它没有未设置为查询尚未完成。第二次按下按钮时,您正在访问现已完成的第一个查询的结果。

您可以使用完成闭包(在 Objective-C 中称为块,因此函数名称的 WithBlock 部分可以处理结果并在需要时显示错误。

您还可以通过使用 whereKey 仅检索您所关注的用户来提高查询效率;

import UIKit
import Parse
import Bolts

var userToAdd=""

class AddFriendViewController: UIViewController {

@IBOutlet var addFriendLabel: UIButton!
@IBOutlet var searchUserTF: UITextField!
override func viewDidLoad() {
    super.viewDidLoad()
    addFriendLabel.setTitle("", forState: .Normal)
    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func searchButtonPressed(sender: AnyObject) {

    if searchUserTF.text != "" {
       let username=searchUserTF.text
        var query = PFUser.query()
        query.whereKey("username", equalTo:username)
        query?.findObjectsInBackgroundWithBlock({ (objects:[PFObject]?, error:NSError?) -> Void in

            if (error != nil) {
               print(error)
            } else {
               if objects!.count >0 {
                   self.addFriendLabel.setTitle("Share myEvents with \(username)", forState: .Normal)
                   self.userToAdd=username
               } else {
                   self.userToAdd=""
                   let alertController = UIAlertController(title: "Username not found!", message: "A user with this username does not exist, please check the spelling or your internet connection", preferredStyle: .Alert)
                   let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
                   alertController.addAction(action)
                   self.presentViewController(alertController, animated: true, completion: nil)
             }
         })
    }
}