swift - 为什么我的模型没有在视图控制器中显示它的成员?
问题描述
我有一个名为 Profile 的模型,有 2 个成员posPoints
和negPoints
. 我正在尝试在名为MyProfileViewController
. 但是,当我输入profiles.posPoints
时,Xcode 无法识别它并给我这个错误
“[Profile]”类型的值没有成员“posPoints”
static func show(for user: User = User.current, completion: @escaping (Profile?) -> Void) {
let profileRef = Database.database().reference().child("profile").child(user.username)
let ref = Database.database().reference().child("profile").child(user.username).child(profileRef.key ?? "")
ref.observeSingleEvent(of: .value, with: { (snapshot) in
guard let profile = Profile(snapshot: snapshot) else {
return completion(nil)
}
completion(profile)
})
}
import Foundation
import FirebaseDatabase.FIRDataSnapshot
class Profile {
// MARK - Properties
var key: String?
let posPoints: Int
let negPoints: Int
init?(snapshot: DataSnapshot) {
guard !snapshot.key.isEmpty else {return nil}
if let dict = snapshot.value as? [String : Any]{
let posPoints = dict["posPoints"] as? Int
let negPoints = dict["negPoints"] as? Int
self.key = snapshot.key
self.posPoints = posPoints ?? 0
self.negPoints = negPoints ?? 0
}
else{
return nil
}
}
}
(在 MyProfileViewController 的 viewDidLoad 中)
ProfileService.show { [weak self] (profiles) in
self?.profiles = profiles
}
myPointsLabel.text = profiles.posPoints
}
Firebase 数据库视图
解决方案
您的代码存在以下问题viewDidLoad
。
1-在获取完成myPointsLabel
的地方进行更新。completionHandler
profiles
2- UI 更新应该在主线程上完成。
3-profile
首先,从 中提取所需array
的profiles
,然后是接入点并将其转换为String
。
您的代码应如下所示,
var profile: Profile?
override func viewDidLoad() {
super.viewDidLoad()
ProfileService.show { [weak self] (profile) in
self?.profile = profile
if let points = profile?.posPoints {
DispatchQueue.main.async {
self?.myPointsLabel.text = String(points)
}
}
}
}
推荐阅读
- vue.js - Vue-Authenticate for Github Login
- html - 如何围绕圆形边距旋转对象(div)?仅 CSS
- javascript - 在 macOS 上从节点项目运行 zeromq 会出错
- swift - 包含 Swift 包时如何解决冗余的协议一致性错误?
- c++ - 空格后不打印单个单词
- c# - 如何从代码中在 CollectionView 中添加 SelectionChanged?
- r - 更改置信区间带的颜色?
- asp.net-core - 如何在 Asp.net Core 中将 LTI 与 nearpod.com 或 MCGRAWHILL 平台集成
- firebase - Firebase 模拟器通过 REST 功能访问数据库
- html - 你好,这里的第一个问题。我一直试图在我的网站上放一张图片,但它不起作用,我就是不知道原因。我的代码 HTML