gpt4 book ai didi

ios - 无法获取 PFUser 字段

转载 作者:行者123 更新时间:2023-11-29 01:16:30 24 4
gpt4 key购买 nike

我想获取当前用户的xp,并显示在标签中。用户的 xp 字段等于 252 但显示为 0。我可以获取其他字段,如电子邮件、用户名和密码,但无法获取 xp 字段的值。代码:

xpRequiredLabel.text = "\(PFUser.currentUser()!["XP"])/300 XP"

我做错了什么?

最佳答案

此表达式 PFUser.currentUser()!["XP"] 返回 AnyObject?。您需要解开这个可选并将其转换为字符串。试试这个:

let userXP = PFUser.currentUser()!["XP"] as! String
xpRequiredLabel.text = "\(userXP)/300 XP"

或者这个(不太容易出错):

if let userXP = PFUser.currentUser()?["XP"] as? String {
xpRequiredLabel.text = "\(userXP)/300 XP"
}

更新

事实证明,您必须在访问新属性之前从服务器获取对象。因此,您的代码应如下所示:

let user = PFUser.currentUser()!
user.fetch()
let userXP = ["XP"] as! Int // If you have "Number" as your column datatype
xpRequiredLabel.text = "\(userXP)/300 XP"

请注意,fetch() 会阻塞 UI。您还可以使此代码异步:

if let user = User.currentUser() {
user.fetchInBackgroundWithBlock({ (result, error) -> Void in
if let u = result as? PFUser {
if let userXP = u["XP"] as? Int {
self.xpRequiredLabel.text = "\(userXP)/300 XP"
}
}
})
}

关于ios - 无法获取 PFUser 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35119709/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com