Reputation: 66
I'm writing an app that will help me update my database on parse and I'm trying to load objects into an nstableview.
For whatever reason, I'm returning nil when I make the call in my viewcontroller so I moved the data into my appdelegate to get the objects.
let storyBoard = NSStoryboard(name: "Main", bundle: nil)
let myVC = storyBoard.instantiateControllerWithIdentifier("teacher") as! ViewController
var teachers = [Teacher]()
let query = PFQuery(className: "TeacherList")
query.findObjectsInBackgroundWithBlock {
objects, error in
if let objects = objects {
for object in objects {
let teacher = Teacher()
teacher.name = object["name"] as! String
teacher.email = object["email"] as! String
teacher.subjectsTaught = object["subjectsTaught"] as! [String: String]
teacher.category = object["category"] as! String
teacher.uniqueID = object.objectId!
teachers.append(teacher)
}
}
print(teachers)
myVC.teacherList = teachers
}
As you see, I pass this along to my VC. So I understand that I need to reload the data as viewDidLoad() will be called before the data has been downloaded. I've tried putting tableView.reloadData() in didSet for teacherList and just in case that's set before the viewloads, I even throw it in viewdidload.
var teacherList: [Teacher]? {
didSet {
print("got set")
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.setDelegate(self)
tableView.setDataSource(self)
tableView.reloadData()
}
However, no matter what, my tableview is nil for anything that happens after viewdidload. I've also tried optional channing in my getSet. I should also say that I'm brand new to OSX programming as I've done most of my programming for iOS.
I can put the query in my VC but whenever I run the query, I return nil.
Upvotes: 0
Views: 430
Reputation: 285072
PFQuery
works asynchronously, the data is returned much later - in terms of computer speed – after viewDidLoad
exits.
Reload the table view in the block right after the array has been populated on the main thread.
var teachers = [Teacher]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.setDelegate(self)
tableView.setDataSource(self)
let query = PFQuery(className: "TeacherList")
query.findObjectsInBackgroundWithBlock { [unowned self] (objects, error) in
if let objects = objects {
for object in objects {
let teacher = Teacher()
teacher.name = object["name"] as! String
teacher.email = object["email"] as! String
teacher.subjectsTaught = object["subjectsTaught"] as! [String: String]
teacher.category = object["category"] as! String
teacher.uniqueID = object.objectId!
self.teachers.append(teacher)
}
}
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
print(self.teachers)
}
}
Upvotes: 1