Hello I want to get some data from my parse.com class called "Tags" in this class there are two 3 cols "objectID", "username" and "tagtext". I want to read a record finding by ID and afterwords I want to save "useername" and "tagtext" into two strings. I have done it like it is in the parse.com documentation:
@IBAction func readAction(sender: UIButton) {
var query = PFQuery(className:"Tags")
query.getObjectInBackgroundWithId("IsRTwW1dHY") {
(gameScore: PFObject?, error: NSError?) -> Void in
if error == nil && gameScore != nil {
println(gameScore)
} else {
println(error)
}
}
let username = gameScore["username"] as! String
let tagtext = gameScore["tagtext"] as! String
println(username)
println(tagtext)
}
I get an error called fatal error: unexpectedly found nil while unwrapping an Optional value
, please tell me what is wrong in my code.
My class:

The problem is that:
let username = gameScore["username"] as! String
let tagtext = gameScore["tagtext"] as! String
gameScore["username"]
and gameScore["tagtext"]
can return nil values, and when you say as! String
you say that it will be a String, and it is nil.
Try something like:
let username = gameScore["username"] as? String
let tagtext = gameScore["tagtext"] as? String
your error is happening because of that, but your final code should look like this:
@IBAction func readAction(sender: UIButton) {
var query = PFQuery(className:"Tags")
query.getObjectInBackgroundWithId("f3AXazT9JO") {
(gameScore: PFObject?, error: NSError?) -> Void in
let username = gameScore["username"] as? String
let tagtext = gameScore["tagtext"] as? String
println(username)
println(tagtext)
if error == nil && gameScore != nil {
println(gameScore)
} else {
println(error)
}
}
}
Because the getObjectInBackgroundWithId
is async.
You are trying to read from your response object gameScore
but it is still nil
because getObjectInBackgroundWithId
is an asynchronous method meaning that it will return a result once it is finished. Put the two lines inside the handler and start from there.
来源:https://stackoverflow.com/questions/30198787/error-while-retrieving-data-from-parse-com