I am using @@Binding which i am passing to function but it causes memory leak and app freezes.
import SwiftUI
struct BottomView: View {
var accessibilityID: String
var viewModel: ViewModel
@Binding var selectedPoductDetails: [String: SelectedProductDetail]
init(accessibiltyID: String, viewModel: ViewModel selectedPoductDetails: Binding<[String: SelectedProductDetail]>) {
self.viewModel = viewModel
self.accessibilityID = accessibiltyID
self._selectedPoductDetails = selectedPoductDetails
}
var body: some View {
VStack {
HStack {
let totalAmount = viewModel.totalAmount(selectedPoductDetails:
selectedPoductDetails)
Text(totalAmount)
}
}
}
My function in another class is
func totalAmount(selectedPoductDetails: [String: SelectedProductDetail]) -> String {
self.selectedProductDetails = selectedPoductDetails
let amount = selectedPoductDetails.reduce(into: 0, { $0 += $1.value.amount })
return amount
}
Why memory leak and app freeze? i am comment code
let totalAmount = viewModel.totalAmount(selectedPoductDetails:
selectedPoductDetails)
everything works fine.
what am I doing wrong?
You just cycles calls, because assigning property activates binding, which activates update, which calls calculable body, which calls viewModel.totalAmount
again... and go on...
just remove
func totalAmount(selectedPoductDetails: [String: SelectedProductDetail]) -> String {
// self.selectedProductDetails = selectedPoductDetails // << this !!
let amount = selectedPoductDetails.reduce(into: 0, { $0 += $1.value.amount })
return amount
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.