Alvin
Alvin

Reputation: 539

Retrieve the List property count of realm for tableview Swift

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!

Upvotes: 2

Views: 1930

Answers (2)

Jay
Jay

Reputation: 35648

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
}

Upvotes: 2

Arasuvel
Arasuvel

Reputation: 3012

Have you tried query logic.

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

or

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

Upvotes: 0

Related Questions