How to query comma separated String

2020-03-26 swift realm

Example:

class MyObject: Object {
    @objc dynamic var linkedServerIds: String?
}

The linkedServerIds may contain comma separated String. example:

linkedServerIds = "18305,13423,11539,11234"

Currently if we want objects that linkedServerIds contains 13423 OR 11234 we do:

Results<MyObject>.filter({
    if let linkedServerIds =  $0.linkedServerIds?.components(separatedBy: ","),
        linkedServerIds.contains(where: { ["13423", "11234"].contains($0) }) {
        return true
    }
    return false
})

This filter will return Array of MyObject and not Results<MyObject>

Is it possible to perform similar filter using NSPredicate? So we can keep the return in Results<MyObject>

TIA!

Answers

I'm not very familiar with realm, however your NSPredicate should be something like this.

NSPredicate(format: linkedServerIds CONTAINS %@, ["13423","11234"])

Obviously, replacing "["13423","11234"]" with whatever argument you are evaluating.

Related