Retrieve the List property count of realm for tableview Swift

强颜欢笑 提交于 2019-12-06 06:07:54

I would probably rename the var dog to var dogs to indicate it may contain more than one dog.

Here's a straightforward solution that prints the owners name and dog count.

do {
    let realm = try Realm()
    let people = realm.objects(Person.self)

    for person in people {
        let name = person.personName
        print(name)

        let dogs = person.dogs
        print(dogs.count)
    }

} catch let error as NSError {
    print(error.localizedDescription)
}

A Realm List has Array functionality so it can be iterated over, count is available and can also be filtered.

And the code in your question

let owners = realm.objects(Person.self)

will assign all Person objects in Realm to the owners var (an array of Person) so it's not one person it would be all of them which is why it doesn't have a .dog property.

You will need to establish which person is supposed to be in each section of the tableView, query Realm for that person and then return person.dogs.count.

The code to determine how you determine which person goes in which section isn't shown in the original question but lets assume you want person 0 in section 0 (there may be an ordering issue so this is just conceptual)

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let owners = realm.objects(Person.self).sorted('name')
    let thisOwner = owners[section]
    let dogCount = thisOwner.dogs.count
    return dogCount
}

Have you tried query logic.

realm.objects(Person).filter("dogs.@count > 0")

or

realm.objects(Person).filter("ANY dogs.@count > 0")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!