Search code examples
swiftxcodeparse-platform

Parse - Xcode - Using data from a Query outside of the Query


I am fairly new to Swift and Parse. I am having trouble with queries. I cannot get my list pickerData to contain the data provided from my query. With this issue, I cannot push information to a picker I have set up

These are my declared variables:

    var users = [PFObject]() //array to hold users
    var pickerData: [String] = [String]() //array to hold picker items

And here is where my issue arises:

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.AssignToPicker.delegate = self
        self.AssignToPicker.dataSource = self

        // Do any additional setup after loading the view.
        
        let query = PFUser.query()
        query?.findObjectsInBackground(block: { users, error in
            if users != nil{
                self.users = users!
                for user in self.users {
                    self.pickerData.append(user["username"] as! String)
                }
                print("Printing contents of pickerData INSIDE of query:")
                for item in self.pickerData {
                    print(item)
                }
            }
        })
        
        print("printing content of pickerData outside of query:")
        for item in self.pickerData {
            print(item)
        }
    }

The for loop within my query provides me with the correct information. The for loop outside of my query provides me with nothing. If I were to set pickerData as such pickerData = ["name1", "name2"] everything would be working perfectly. But as it is now, when I load my pickerData within the query, it seems to be erased after I leave it

The essence of my question is how do I get this query information to save outside of the findObjectsInBackgroundmethod?


Solution

  • the findObjectsInBackground method happens asynchronous with the rest of the file. This means that it kind of lags behind everything else. The data that you set inside the query is only ready at the end of the compilation of the file. This means when you try to do

    for item in self.pickerData {
                print(item)
            }
    

    outside of your query, pickerData has not yet been populated.

    The is a synchronous option out there but I'm not sure if it is beneficial to your subject

    let query = PFQuery(className: "yourClassName")
    do {
        //synchronous
        let item = try query.getObjectWithId(yourIdHere)
    } catch {
        print("error")
    }
    

    This query happens synchronously. The data you save in item can be used immediately afterward