Realm result - Last in collection

I Have the following model

    class Process: Object {

     @objc dynamic var processID:Int = 1 
     let steps = List<Step>()
    }

    class Step: Object {

    @objc private dynamic var stepCode: Int = 0 
    @objc dynamic var stepDateUTC: Date? = nil 
        var stepType: ProcessStepType {
            get { return ProcessStepType(rawValue: stepCode) ?? .created }
            set { stepCode = newValue.rawValue }
        }

    }


    enum ProcessStepType: Int { // to review - real value
        case created = 0
        case scheduled = 1
        case processing = 2
        case paused = 4
        case finished = 5

    }

A process can start, processing , paused , resume (to be in step processing again), pause , resume again, etc. the current step is the one with the latest stepDateUTC

I am trying to get all Processes, having for last step ,a step of stepType processing "processing ", ie. where for the last stepDate, stepCode is 3 . I came with the following predicate… which doesn’t work. Any idea of the right perform to perform such query ?

my best trial is the one. Is it possible to get to this result via one realm query .

let processes = realm.objects(Process.self).filter(NSPredicate(format: "ANY steps.stepCode = 3 AND NOT (ANY steps.stepCode = 5)")

let ongoingprocesses = processes.filter(){$0.steps.sorted(byKeyPath: "stepDateUTC", ascending: false).first!.stepType == .processing}

what I hoped would work

NSPredicate(format: "steps[LAST].stepCode = \(TicketStepType.processing.rawValue)")

I understand [LAST] is not supported by realm (as per the cheatsheet). but is there anyway around I could achieve my goal through a realm query?

This is a cross post to Stack Overflow post Cannot get Realm result for objects filtered by the latest (nsdate) value of a property of a collection property swift (the example is clearer)

It’s a good idea to keep posts in one place so they have focus. The answer is there is no ‘3’ stepCode - at least as defined in ProcessStepType

Note that filtering with {$0.steps.sorted may have unintended results as that’s a swift sort, returns an array but ‘disconnects’ those objects from Realm because they are not in a Realm Results object. If you want the objects to remain connected to Realm, use realm sorting to return a Results object.

Also, while realm doesn’t support [LAST] in the context you used, if you sort the results by timestamp the last item will be… the last item e.g. the most current.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.