如何解决查看模型留在内存中 SwiftUI 和 Firebase
我在链接到 Firestore 数据库的应用程序的一部分中使用了 MVVM 架构。玩家列表是我带入我的应用程序的内容。问题是我正在创建许多 Playerviewmodel 实例,它们都保留在内存中,导致在某些时候使用高达 8GB 和 100 万个实例,我不知道为什么。
我通过存储库引入玩家列表:
class PlayerRepository: ObservableObject{
static let shared = PlayerRepository()
var db = Firestore.firestore()
@Published var players = [DBPlayer]()
@Published var chosenPlayer: DBPlayer? = nil
func loadData(teamID: String){
let userID = Auth.auth().currentUser?.uid
self.players = []
db.collection("players")
.order(by: "name")
.whereField("userID",isEqualTo: userID!)
.whereField("teamID",isEqualTo: teamID)
.addSnapshotListener { (querySnapshot,error) in
if let querySnapshot = querySnapshot{
self.players = querySnapshot.documents.compactMap { document in
do{
let x = try document.data(as: DBPlayer.self)
return x
}
catch{
print(error)
}
return nil
}
}
}
}
}
找到的每个玩家都被放入数据结构 DBPlayer:
struct DBPlayer: Identifiable,Equatable,Codable{
@DocumentID var id: String?
var userID: String?
var teamID: String
var name: String
var matchesPlayed: Int = 0
var secondsPlayed: Int = 0
var totalTries: Int = 0
var totalConversions: Int = 0
var totalPenaltyKicks: Int = 0
var totalDropGoals: Int = 0
var totalPenaltiesConc: Int = 0
var totalFreeKicksConc: Int = 0
static func ==(lhs: DBPlayer,rhs: DBPlayer) -> Bool {
return lhs.name == rhs.name && lhs.id == rhs.id
}
}
我还使用了 PlayerListviewmodel 和 Playerviewmodel,可以在下面找到:
class PlayerListviewmodel: ObservableObject{
@Published var playerRepository = PlayerRepository.shared
@Published var playerviewmodels = [Playerviewmodel]()
private var playerCancellables = Set<AnyCancellable>()
init(){
playerRepository.$players.map { players in
players.map { player in
Playerviewmodel(player: player)
}
}
.assign(to: \.playerviewmodels,on: self)
.store(in: &playerCancellables)
}
}
class Playerviewmodel: ObservableObject,Identifiable{
@Published var playerRepository = PlayerRepository.shared
@Published var player: DBPlayer
var id = ""
@Published var playerName = ""
private var cancellables = Set<AnyCancellable>()
init(player: DBPlayer){
self.player = player
$player
.map{ player in
player.name
}
.assign(to: \.playerName,on: self)
.store(in: &cancellables)
$player
.map { player in
(player.id ?? "")
}
.assign(to: \.id,on: self)
.store(in: &cancellables)
$player
.dropFirst()
.debounce(for: 0.8,scheduler: RunLoop.main)
.sink { player in
self.playerRepository.updatePlayer(player)
}
.store(in: &cancellables)
}
}
我对内存管理不是很了解,但我认为我需要在某些时候使用弱,但我不知道在哪里。任何帮助将不胜感激!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。