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

点击API列表项存入SwiftData后列表消失问题求助

问题原因

你直接将API返回的未托管GroceryItem实例插入SwiftData上下文,导致该实例转为托管对象。SwiftData托管对象的内部标识(如objectID)会发生变更,而viewModel.groceryItems数组仍保留这个已托管的实例,SwiftUI的List无法正确识别数组中的元素,最终导致API List消失。

解决方案

修改GroceryViewModel的saveGroceryItem方法,创建新的GroceryItem实例复制原对象属性,再插入上下文,避免修改原API数据数组中的实例:

func saveGroceryItem(_ item: GroceryItem) {
    // 基于原对象属性创建新实例
    let newGroceryItem = GroceryItem(
        id: item.id,
        name: item.name,
        quantity: item.quantity // 替换为你的实际属性
    )
    context.insert(newGroceryItem)
    print("Added to grocery list")
}

额外注意事项

  1. 确保GroceryItem的Model定义正确,id建议设置为唯一属性:
@Model
class GroceryItem: Identifiable {
    @Attribute(.unique) var id: UUID
    var name: String
    var quantity: Int
    
    init(id: UUID = UUID(), name: String, quantity: Int) {
        self.id = id
        self.name = name
        self.quantity = quantity
    }
}
  1. 可选优化:添加重复校验,避免插入相同ID的商品:
func saveGroceryItem(_ item: GroceryItem) {
    // 查询是否已存在相同ID的商品
    let fetchDescriptor = FetchDescriptor<GroceryItem>(predicate: #Predicate { $0.id == item.id })
    guard try? context.fetch(fetchDescriptor).isEmpty else {
        print("Item already exists")
        return
    }
    
    let newGroceryItem = GroceryItem(
        id: item.id,
        name: item.name,
        quantity: item.quantity
    )
    context.insert(newGroceryItem)
    print("Added to grocery list")
}

内容的提问来源于stack exchange,提问作者Abdullah Ajmal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 15:47:24