【问题标题】:Count number of items in Realm Object List not working计算领域对象列表中的项目数不起作用
【发布时间】:2018-05-15 22:02:43
【问题描述】:

我正在尝试计算领域列表(包含在“WorkoutSessionObject”中)中的练习数量,以填充表格视图的正确行数,但由于某种原因,我无法计算出它不让我可以访问该物业吗?

它肯定是在检索 WorkoutSessionObject,因为我已经尝试过打印它。

代码如下:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

//filter for a specific workout
    let predicate = NSPredicate(format: "workoutID = %@", workoutID)
    let workoutExercises = realm.objects(WorkoutSessionObject.self).filter(predicate)

//access the 'exercises' list and count it - this isn't working?
    let numberOfExercises = workoutExercises.exercises.count
    return numberOfExercises
}

我已经以类似的方式访问属性来填充单元格,但我显然在那里使用 index.row。

我得到的错误是

“结果”类型的值没有成员“练习”

在代码中标记为不工作的行上

研究这里有一个答案Retrieve the List property count of realm for tableview Swift,但这似乎不会返回范围内的计数(它允许在示例中打印,但这在我的代码中不起作用)

即我也试过这个,它不起作用,因为在范围之外无法访问计数:

   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let predicate = NSPredicate(format: "workoutID = %@", workoutID)

//the below works to count but then not accessible outside scope to define number of rows :-(

        let workoutExercises = realm.objects(WorkoutSessionObject.self).filter(predicate)
        for exercises in workoutExercises {
            let exerciseCount = exercises.exercises.count
            return exerciseCount
        }
//return exercise count for table rows - this doesn't work because not in scope
        return exerciseCount
    }

有什么想法吗?

【问题讨论】:

  • 你正在从你的'for'循环中返回,这不是你应该做的。如果你想知道你有多少练习,你需要增加计数,然后返回最终的计数。

标签: ios swift uitableview realm swift4


【解决方案1】:

问题是 Realm 的 filter 保留了原始类型(就像 Swift 的内置 filter),所以 workoutExercises 的类型实际上是 Results<WorkoutSessionObject> 而不是单个 WorkoutSessionObject

如果您知道WorkoutSessionObjectworkoutID 属性始终是唯一的,您只需在Results 实例上调用first

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

如果你知道总会有一个匹配的WorkoutSessionObject,你可以强制解开workoutExercises

如果workoutID实际上是一个primaryKey,最好使用let workoutExercises = realm.object(ofType: WorkoutSessionObject.self, forPrimaryKey: workoutID)而不是过滤查询。

【讨论】:

  • 我已经添加了主键并按照建议更改了查询 - 它正在成功写入 Realm,但现在在加载 tableview 之前崩溃,错误为“*** Terminating app due to unaught exception” RLMException',原因:'索引 1 超出范围(必须小于 1)。 *** 首先抛出调用栈:"
  • 啊,谢谢——即使是那个问题也有帮助。我很快用谷歌搜索断点,发现这是我代码中的另一个点,我使用了上面的谓词方法。不知道为什么在我设置主键后会中断,但我现在已将其更改为主键过滤器并且它工作正常 - 谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多