3

I am trying to populate an array with a query from my parse database. When I try to print out the content of the array, I get an EXC_BAD_INSTRUCTION error. It doesn't seem like I'm properly appending new elements into my array, I'd appreciate any sort of tips

func loadSampleTasks() {

    tasks = [Task]()
    let query = PFQuery(className: "Task")
    query.whereKey("TaskName", equalTo: "kenny")
    query.findObjectsInBackgroundWithBlock() {
        (objects: [PFObject]?, error: NSError?) -> Void in
        if error == nil && objects != nil {
            self.parseResults(objects!)
            print(self.tasks) // this prints out Kenny object as expected
        }
    }
    print(tasks) // prints an empty array
}

func parseResults(objects: Array<PFObject>){

    for object in objects { //looping through returned data
        print("no error in Parse lookup")
        let parseResult1 = Task(name: object["TaskName"] as! String)
        parseResult1?.completed = object["Completed"] as! Bool
        print("Parse result in object loop: \(parseResult1!.name)")
        tasks.append(parseResult1!)
    }

}

Any help much appreciated!

2
  • This is happening because you're getting your parse results in a closure, which means it may execute after the function itself has already returned. Commented Dec 4, 2015 at 16:44
  • What can I do to fix this? Commented Dec 4, 2015 at 17:08

2 Answers 2

1

To what thefredelement said, "This is happening because you're getting your parse results in a closure, which means it may execute after the function itself has already returned." Before this happens, though, it won't work properly and you'll come back with that error.

Sign up to request clarification or add additional context in comments.

2 Comments

I don't quite understand why there would be an error. It seems like I'm calling print after the closure so it should be fine?
Ha, I'm too late! I took a lunch break and then tried to scout around for the answer and found that I received the same error in fake scripts after I was calling something outside of its respective function. But it looks like you already got to that point, so I'm a tad too late. Glad you got it to work! :)
0

I got it to work. I had to tableView.reloadData() within the closure. Thank you so much for the help!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.