0

I am using Parse for a database.

Problem: I am querying the database and saving an object, but it does not seem to be saving outside the query function. I think it is because I need to refresh a variable or something but I have no idea how to do that.

Relevant code:

class AddClassViewController: UIViewController {

var classroom = Classroom()

var checkClassList: [Classroom] = []

@IBAction func enrollClassButton(sender: AnyObject) {
    self.classroom.classCode = classCodeText.text.uppercaseString
    self.classroom.year = yearText.text
    self.classroom.professor = professorNameText.text

    ClassListParseQueryHelper.checkClass({ (result: [AnyObject]?,error: NSError?) -> Void in
        self.checkClassList = result as? [Classroom] ?? []
        //count is 1 inside here
        println(self.checkClassList.count)
        }, classCode: self.classroom.classCode!)

    //count is 0 out here
    println(self.checkClassList.count)


}

//this gets class with matching classcode
static func checkClass(completionBlock: PFArrayResultBlock, classCode: String){
    let query = PFQuery(className: "Classroom")
    query.whereKey("ClassCode", equalTo: classCode)
    query.findObjectsInBackgroundWithBlock(completionBlock)
}
Michael Ninh
  • 772
  • 2
  • 10
  • 23
  • You don't need to "refresh a variable"(whatever that means). You are missing the fact that you are making an *asynchronous* call. Rather than giving you a straightforward answer, I suggest you read up a little on asynchronous programming and how its handled in Swift. – Roshan Sep 04 '15 at 23:40
  • Wow I totally overlooked this. This should be the solution. Thanks! – Michael Ninh Sep 04 '15 at 23:42
  • My pleasure. And since I didn't give a specific solution, I would suggest you put up the exact solution yourself. :) – Roshan Sep 04 '15 at 23:45
  • Still don't know the solution...I don't know how to get the data result from query.findObjects(). I only know how to use the async method – Michael Ninh Sep 05 '15 at 00:55
  • You might wanna look at http://stackoverflow.com/questions/31878929/how-do-i-access-variables-that-are-inside-closures-in-swift/31879069#31879069 – Roshan Sep 05 '15 at 01:16

1 Answers1

0

This is how I solved this:

class ClassListParseQueryHelper{
//this gets class with matching classcode
static func checkClass(classCode: String) -> [PFObject]{
    let query = PFQuery(className: "Classroom")
    query.whereKey("ClassCode", equalTo: classCode)
    var test = query.findObjects() as! [PFObject]
    return test
}

self.checkClassList = ClassListParseQueryHelper.checkClass(self.classroom.classCode!) as! [Classroom]
Michael Ninh
  • 772
  • 2
  • 10
  • 23