Retrieve the List property count of realm for tableview Swift

烂漫一生 提交于 2019-12-22 18:05:22

问题


I am using Realm 3 and Swift 4 and still new to Realm and Swift. Need a guidance here :)

Given this realm model

class Person: Object, Mappable {
    let dog = List<Dog>()

    required convenience init?(map: Map) {
        self.init()
    }
}

How can I get the dog count of each person?

What i want to achieve is there are multiple sections on my table view and for each person there will be dog list for the respective person.

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

    let owner = realm.objects(Person.self)
    return owner.dog.count // This is not working. What should I change it to ?
}

I have been searching through the web but couldn't find any guide on such problem.

Any help given is highly appreciated. Thanks!


回答1:


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
}



回答2:


Have you tried query logic.

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

or

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


来源:https://stackoverflow.com/questions/47652919/retrieve-the-list-property-count-of-realm-for-tableview-swift

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