所以我试图从Parse那里得到一个对象,它给我一个关于可选的错误,我无法理解。错误与getObjectInBackgroundWithId
部分有关,我无法弄清楚为什么我的解包不起作用。
import UIKit
import Parse
class ViewController: UIViewController {
var question: String!
var answers: [String]!
var answer: String!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func CallData() {
var query : PFQuery = PFQuery(className: "QuestionsAndAnswers")
query.getObjectInBackgroundWithId("myParseCode") {
(ObjectHolder : PFObject?, error : NSError?)-> Void in
// error is here^^
if (error == nil) {
self.question = objectHolder["Question"] as? String
self.answers = objectHolder["Answers"] as? Array
self.answer = objectHolder["Answer"] as? String
if (self.answers?.count > 0) {
self.questionLabel.text = self.question
}
} else {
println("Theres been an error")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
答案 0 :(得分:0)
您需要确保在将字符串分配给您的类属性之前将其解包,因为您已声明该字符串是非可选的(使用!
)。您可以使用optional binding替换您提供的代码中的以下代码行:
self.question = objectHolder["Question"] as? String
self.answers = objectHolder["Answers"] as? Array
self.answer = objectHolder["Answer"] as? String
使用:
if let question = objectHolder["Question"] as? String {
self.question = question //it's now unwrapped and not an optional
}
if let answers = objectHolder["Answers"] as? Array {
self.answers = answers
}
if let answer = objectHolder["Answer"] as? String {
self.answer = answer
}