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

无法获取Realm Object List中条目数量的问题排查

解决Realm Results无法访问exercises属性及行数统计问题

我明白你遇到的问题了——咱们一步步来拆解和解决:

问题根源分析

  1. 第一段代码报错原因:
    realm.objects(WorkoutSessionObject.self).filter(predicate) 返回的是 Results<WorkoutSessionObject> 类型,这是Realm的集合对象,代表匹配查询条件的所有WorkoutSessionObject实例。集合本身并没有exercises属性,只有单个WorkoutSessionObject实例才有这个List类型的属性,所以直接调用workoutExercises.exercises会报错 Value of type 'Results' has no member 'exercises'。

  2. 第二段代码的问题:
    你在循环里直接return exerciseCount,这会导致函数在遍历第一个WorkoutSessionObject时就直接返回了,无法处理多个对象的情况;而且如果查询结果为空(没有匹配的WorkoutSessionObject),循环不会执行,最后的return exerciseCount会因为变量未定义而报错。

正确的解决方案

假设你的workoutID是唯一的(每个workoutID对应一个WorkoutSessionObject),我们只需要获取这个唯一的对象,再访问它的exercises属性即可:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let predicate = NSPredicate(format: "workoutID = %@", workoutID)
    // 用first获取单个匹配的WorkoutSessionObject(因为workoutID唯一)
    if let targetWorkout = realm.objects(WorkoutSessionObject.self).filter(predicate).first {
        // 返回该对象下exercises的数量
        return targetWorkout.exercises.count
    }
    // 如果没有找到匹配的对象,返回0避免崩溃
    return 0
}

如果你的workoutID可能对应多个WorkoutSessionObject,需要统计所有对象的exercises总数,可以这样写:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let predicate = NSPredicate(format: "workoutID = %@", workoutID)
    let workoutSessions = realm.objects(WorkoutSessionObject.self).filter(predicate)
    // 遍历所有会话,累加每个会话的exercises数量
    var totalCount = 0
    for session in workoutSessions {
        totalCount += session.exercises.count
    }
    return totalCount
}

额外优化建议

可以用guard let来让代码更简洁:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let predicate = NSPredicate(format: "workoutID = %@", workoutID)
    guard let targetWorkout = realm.objects(WorkoutSessionObject.self).filter(predicate).first else {
        return 0
    }
    return targetWorkout.exercises.count
}

这样就能正确获取到你需要的行数啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 10:07:55