首页 > 解决方案 > 为什么我的模型没有在视图控制器中显示它的成员?

问题描述

我有一个名为 Profile 的模型,有 2 个成员posPointsnegPoints. 我正在尝试在名为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 数据库视图

Firebase 数据库

标签: swiftdatabasemodelmember

解决方案


您的代码存在以下问题viewDidLoad

1-在获取完成myPointsLabel的地方进行更新。completionHandlerprofiles

2- UI 更新应该在主线程上完成。

3-profile首先,从 中提取所需arrayprofiles,然后是接入点并将其转换为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)
            }
        }
    }
}

推荐阅读