Swift - 如何创建一个对象的实例,其变量是来自Parse的数据?

时间:2015-05-17 16:14:25

标签: ios swift parse-platform ios8

在我的Xcode项目中,我有一个名为Question的类,包含实例变量:

import Foundation

class QuestionModel {
 let question: String?
 let answers: [String]
}

我在parse.com(名为Question)数据库上有一个类,我创建了一个对象,我添加了三列(一个字符串名称问题,一个名为答案的字符串数组和一个名为date of the question的字符串,以便我可以访问它。)

在我的视图控制器上,我想使用解析中的数据创建类Question的实例:

let newQuestion = QuestionModel()

var query = PFQuery(className:"Questions")
query.whereKey("date", equalTo:"5/17/15")
query.findObjectsInBackgroundWithBlock {
  (objects: [AnyObject]?, error: NSError?) -> Void in

  if error == nil {
    // The find succeeded.
    println("Successfully retrieved \(objects!.count) scores.")
    // Do something with the found objects
    if let objects = objects as? [PFObject] {
      for object in objects {
        newQuestion.options = object["options"] as? [String]
      }
    }
  } else {
    // Log details of the failure
    println("Error: \(error!) \(error!.userInfo!)")
  }

}

println(newQuestion.options)

打印出它找到1个物体 但是当我添加最后一个println时,它打印为nil。为什么不打印我在Parse数据库中添加的字符串?

1 个答案:

答案 0 :(得分:0)

带有完成块的Asynch方法很棘手,因为代码不会按照您在源文件中找到它的顺序执行...

// edit - outside of this method, in the containing class:
var question: QuestionModel

query.findObjectsInBackgroundWithBlock {
  (objects: [AnyObject]?, error: NSError?) -> Void in
      self.question.options = // ...
      // use objects here, e.g. what your posted code does
      // update your UI with objects here, because they are valid here
      println("this runs SECOND")
      // no matter what you assign in here...
}

// ...it won't be accessible here, because this code runs *before* the code
// in the block
println("this runs FIRST")