Search code examples
iosrealmrealm-mobile-platform

Realm DB ios swift. Get number of occurances of a keyword in List


I have an object as below

@objcMembers class MyObject: Object {
    dynamic var name: String = ""
    dynamic var myArray = List<MyArray>()
}

class MyArray: Object {
    @objc dynamic var number = 0
    @objc dynamic var text = ""
}

How can I get number of occurrences of a keyword in text.

Suppose text contain sentences like

  1. This world is very beautiful. This is correct
  2. This is a beautiful car

So if I search for This, I should get 3. If I search for beautiful, I should get 2


Solution

  • The first thing to do it to modify the code to make it more readable.

    List properties are defined like this and I also changed the property name to better match what it is (not an array)

    class MyObject: Object {
        @objc dynamic var name: String = ""
        let textList = List<TextClass>() //fixed definition
    }
    

    while we're at it, lets update the object stored in that list with a better fitting class name

    class TextClass: Object {
        @objc dynamic var number = 0
        @objc dynamic var text = ""
    }
    

    And then here's the code to read in all of the MyObject objects, iterate over the textList property and count the total amount of occurrences of a given word.

    let myObjectResults = realm.objects(MyObject.self)
    
    let wordToFind = "This" //the word to find
    for obj in myObjectResults {
        var count = 0
        let theList = obj.textList
        for textObj in theList {
            let wordCount = textObj.text.lowercased().components(separatedBy: wordToFind.lowercased()).count - 1
            count += wordCount
        }
        print("object: \(obj.name) had: \(count) occuranced of string: \(wordToFind)")
    }
    

    and the results when searching for the word 'This'

    object: some object had: 3 occurrences of string: This
    

    When searching for the word Beautiful here's the output

    object: some object had: 2 occurrences of string: Beautiful
    

    The reason we're using iteration in the case is because we're actually performing a substring search of the realm property text. While Realm filtering is great at returning Results objects where objects property(s) match a particular query, it's not great at internal string manipulation.

    There may be an NSPredicate solution as well.