我从Parse导入数据并尝试将其放入页面视图控制器中。查询的代码是正确的,但它没有被调用。它尝试将数组内的对象添加到pageviewcontroller,但这些数组是空的,它们只会在查询后填充。那么如何确保查询运行并首先填充数组?
override func viewDidLoad() {
super.viewDidLoad()
testRetrieveInfo()
}
func retrieveinfo(callback:([String])->Void){
let query = PFQuery(className: "Animals")
query.findObjectsInBackgroundWithBlock { (objects:[PFObject]?, error: NSError?) in
if(error == nil){
for object in objects!{
if let importname = object["Name"] as? String{
self.name = NSArray(object: importname)
print(self.name) //Nothing prints, I also breakpoint and it crashes first, crash location is above in viewDidLoad
}
}
}else{
print(error)
}
}
}
}
func testRetrieveInfo(){
self.retrieveInfo { (results:[String]) -> Void in
//Setup here the PageViewController
self.pageViewController.storyboard?.instantiateViewControllerWithIdentifier("PageVC") as? UIPageViewController
self.pageViewController.dataSource = self
var startVC = self.viewControllerAtIndex(0) as? Jwasy
var viewControllers = NSArray(object: startVC!)
self.pageViewController.setViewControllers(viewControllers as? [UIViewController], direction: .Forward , animated: true, completion: nil)
self.pageViewController.view.frame = CGRectMake(0, 30, self.view.frame.width, self.view.frame.height)
self.addChildViewController(self.pageViewController)
self.view.addSubview(self.pageViewController.view)
self.pageViewController.didMoveToParentViewController(self)
print("called")//not printed
}
}
答案 0 :(得分:1)
要在下载数据时收到通知,您有不同的选项(但最基本的是在查询的回调中设置PageViewController):
0 - 您可以创建一个方法来设置PageViewController并在查询的回调中调用。
1 - 创建自己的回调
func retrieveInfo(callback:([String])->Void){
//Inside your query callback you're going to call yours
let query = PFQuery(className: "Animals")
query.findObjectsInBackgroundWithBlock { (objects:[PFObject]?, error: NSError?) in
if(error == nil){
var results:[String] = []
for object in objects!{
if let importname = object["Name"] as? String{
self.results.append(importname)
}
}
callback(results)
}else{
//Can also create a callback for failure
print(error)
}
}
}
//Used
func testRetrieveInfo(){
self.retrieveInfo { (results:[String]) -> Void in
//Setup here the PageViewController
}
}
2 - 创建代表
3 - 通知中心
注意:强> 您每次都在循环中重新创建名称数组。你能看一下断点的打印屏幕吗?