MVVM架构下iOS添加模型后Cart页面TableView不显示更新数据的问题
Let's break down what's going wrong here and fix it step by step:
1. Immediate Check: Verify Data Reachability in Cart VC
First, confirm your cart ViewController is actually receiving the populated data:
- In your
ViewController(cart VC), add a print statement intableView(_:numberOfRowsInSection:)to check the row count:func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let count = chartViewModel.numberOfRowsInSection(section: section) print("Number of cart items: \(count)") // Add this line return count } - If the count is
0but you confirmed data was added in theadd()method, there's a disconnect in how your ViewModel's data is being passed or initialized.
2. Fix ViewModel Data Handling Issues
Your ViewModel has unnecessary and unsafe code that's causing inconsistencies:
- Remove the redundant line in
add():func add() { guard let newModel = insertedArray else { return } // Replace force unwrap with safe check datasourceModel.dataListArray?.append(newModel) print(datasourceModel.dataListArray) // Delete this line: self.datasourceModel.dataListArray = datasourceModel.dataListArray } - Delete the broken
insert()method entirely (it tries to insert aString?into a[Model]array, which will cause a compile error):// Remove this method func insert(){ add() datasourceModel.dataListArray!.insert(insertedArray?.offerdetailAddName, at: indexPath.row) }
3. Fix IndexPath Bug in HotelViewController
You're using an undefined indexPath variable in your add-to-cart closure—this is likely causing you to pass incorrect data to the cart model:
cell.cartaddCell = {[weak self] in guard let self = self, let indexPath = self.tableView.indexPath(for: $0) else { return } // Safe unwrapping let cartDataSource = DataSourceModel(array: nil) let cartViewModel = ViewModel(withdatasource: cartDataSource) let cartmodel = Model(withoffermodel: self.offerViewModel.datafordisplay(atindex: indexPath)) // Use the valid indexPath cartViewModel.insertedArray = cartmodel cartViewModel.add() let cartViewController = ViewController(nibName: "ViewController", bundle: nil, withViewModel: cartViewModel) self.navigationController?.pushViewController(cartViewController, animated: true) }
4. Add MVVM-Compliant Data Update Notifications
To ensure your TableView refreshes whenever data changes (even for future in-cart updates like deleting items), add a closure to your ViewModel:
- Update your
ViewModelclass:class ViewModel: NSObject { var datasourceModel: DataSourceModel var insertedArray: Model? var finalArray: [Model]? = [] // Add this closure to notify data changes var onDataChanged: (() -> Void)? init(withdatasource newDatasourceModel: DataSourceModel) { datasourceModel = newDatasourceModel print(datasourceModel.dataListArray) } // ... existing methods ... func add() { guard let newModel = insertedArray else { return } datasourceModel.dataListArray?.append(newModel) print(datasourceModel.dataListArray) onDataChanged?() // Trigger refresh } func delete(atIndex indexPath: IndexPath) { datasourceModel.dataListArray?.remove(at: indexPath.row) onDataChanged?() // Trigger refresh } } - Listen for changes in your cart
ViewController:override func viewDidLoad() { super.viewDidLoad() // ... existing setup code ... // Listen for data changes and refresh TableView chartViewModel.onDataChanged = { [weak self] in self?.tableView.reloadData() } self.tableView.reloadData() }
5. Ensure DataSourceModel Initializes a Non-Nil Array
If your DataSourceModel doesn't initialize an empty array when passed nil, your append calls will silently fail. Fix its initializer:
class DataSourceModel { var dataListArray: [Model]? init(array: [Model]?) { self.dataListArray = array ?? [] // Fallback to empty array if input is nil } }
6. Verify Cell Configuration
Double-check your ChartCell's setEventData(charts:) method to ensure it's correctly mapping model properties to UI elements:
func setEventData(charts: Model) { // Example: Make sure you're setting labels with model data nameLabel.text = charts.offerdetailAddName priceLabel.text = "\(charts.offerprice)" print("Configuring cell with: \(charts.offerdetailAddName)") // Add print to confirm }
After applying these fixes, your shopping cart TableView should correctly display the added hotel items.
内容的提问来源于stack exchange,提问作者abel

