此代码在Swift 1.1中运行良好...只是试图找出1.2中的更改以使其不兼容:
@IBAction func load_click(sender: AnyObject) {
var query = PFQuery(className: "myClass")
query.getObjectInBackgroundWithId("MPSVivtvJR", block: { (object:PFObject!, error: NSError) -> Void in
let theName = object["name"] as String
let theAge = object["age"] as Int?
println(theName)
println(theAge)
})
}
它给了我错误:无法调用' GetObjectInBackgroundWithId'使用类型'的参数列表(String,block:(PFObject!,NSError) - > Void)
有什么想法吗?谢谢!
答案 0 :(得分:6)
现在使用Swift 1.2,你应该更加小心打开选项。因此,在您拥有PFObject
和NSError
的闭包内,要么删除感叹号,要么添加问号以使其成为可选项。
然后,更安全地打开您的物体。请尝试如下:
// You can create this in a separate file where you save your models
struct myUser {
let name: String?
let age: Int?
}
// Now this in the view controller
@IBAction func load_click(sender: AnyObject) {
var query = PFQuery(className: "myClass")
query.getObjectInBackgroundWithId("MPSVivtvJR", block: {
(object:PFObject!, error: NSError?) -> Void in
if let thisName = object["name"] as? String{
if let thisAge = object["age"] as? Int{
let user = myUser(name: thisName, age: thisAge)
println(user)
}
}
})
}
答案 1 :(得分:2)
我为此苦苦挣扎,但下面的代码对我有用。
var query = PFQuery(className: "class")
query.whereKey("user", equalTo: PFUser.currentUser()!)
query.orderByDescending("createdAt")
var object = query.getFirstObject()
if let pfObject = object {
data.variable = (pfObject["variable"] as? Float)!
}
答案 2 :(得分:1)
接受的答案对我不起作用。这是做了什么工作:
var query = PFQuery(className: "score")
query.getObjectInBackgroundWithId("j5xBfJ9YXu", block: {
(obj, error)in
if let score = obj! as? PFObject {
println(score.objectForKey("name"))
} else {
println(error)
}
})