You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取UITableView选中单元格的用户UID与UITextField价格并保存至Core Data

解决方案:获取选中单元格数据并保存到Core Data

嘿,我来帮你搞定这个问题!要实现获取选中单元格的userUID和输入的价格,再保存到Expenses实体,我们可以分两步来做:获取选中行的有效数据和写入Core Data。

1. 修改doneButton方法,实现数据收集与保存

直接在你的doneButton点击事件里添加以下逻辑,我会逐行注释说明:

@IBAction func doneButton(_ sender: UIBarButtonItem) {
    // 1. 获取所有选中行的indexPath
    guard let selectedIndexPaths = tableView.indexPathsForSelectedRows else {
        print("请至少选择一个用户")
        return
    }
    
    // 2. 获取Core Data的上下文(从已有的fetchedResultsController中获取)
    guard let context = fetchedResultsController.managedObjectContext else {
        print("无法获取Core Data上下文")
        return
    }
    
    // 3. 遍历每一个选中的行
    for indexPath in selectedIndexPaths {
        // 获取对应的Users实体对象
        let targetUser = fetchedResultsController.object(at: indexPath)
        // 获取对应的CustomCell实例
        guard let cell = tableView.cellForRow(at: indexPath) as? CustomCell else { continue }
        
        // 4. 处理价格输入的合法性(避免空值或非数字导致崩溃)
        guard let priceInput = cell.txtPrice.text, 
              !priceInput.trimmingCharacters(in: .whitespaces).isEmpty, 
              let priceValue = Int(priceInput) else {
            print("用户\(targetUser.userName)的价格输入无效,跳过该记录")
            continue
        }
        
        // 5. 创建Expenses实体并赋值
        let newExpense = Expenses(context: context)
        newExpense.userUID = targetUser.userUID
        newExpense.price = Int64(priceValue) // 注意:如果你的Core Data模型中price是Int32,这里改为Int32(priceValue)
        
        // 6. 保存上下文(可以选择批量保存,这里为了清晰每一条都保存,也可以遍历完统一保存)
        do {
            try context.save()
            print("成功保存用户\(targetUser.userName)的费用记录")
        } catch {
            print("保存失败:\(error.localizedDescription)")
        }
    }
    
    // 7. 保存完成后的操作(比如返回上一页或刷新界面)
    navigationController?.popViewController(animated: true)
}

2. 额外优化建议

  • 批量保存优化:上面的代码每创建一条记录就保存一次,你也可以把context.save()移到遍历循环外面,这样只需要保存一次,性能更好:
    // 遍历完成后统一保存
    do {
        try context.save()
        print("所有选中用户的费用记录已成功保存")
    } catch {
        print("批量保存失败:\(error.localizedDescription)")
    }
    
  • 输入验证增强:可以在CustomCell的txtPrice添加键盘类型限制(比如只允许数字输入),减少无效输入:
    在cellForRowAt方法里添加:
    cell.txtPrice.keyboardType = .numberPad
    
  • 避免Cell复用问题:因为UITableView会复用Cell,如果你在滚动时输入的价格可能会错位,建议在CustomCell中绑定对应的userUID,并在cellForRowAt时恢复对应的数据(不过如果只是在选中后一次性提交,这个问题影响不大)。

验证要点

  • 确保你的Core Data模型中Expenses的price属性类型和代码中的转换类型一致(比如Core Data里是Integer 64,代码用Int64;如果是Integer 32,用Int32)。
  • 确认fetchedResultsController已经正确获取到Users数据,fetchUsers()方法没有问题。

内容的提问来源于stack exchange,提问作者Berkan C.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:58:12