How to create predicate to fetch core data entities by string property sorted as an integer?

104 Views Asked by At

I simply have a Month entity with property

@objc(Month)
class Month: NSManagedObject {
    @NSManaged var identifier: String //202311, 202301, 201912 and so on, always year and month as a components
}

Now I need to fetch all months with identifier between given start and end, for example predicate format:

"identifier >= 202306 AND identifier <= 202311"

How can I do it?

1

There are 1 best solutions below

0
Larme On

You are using the format yyyyMM, so in fact, you can use the String comparison: same count of numbers for each unit (leading zeros if needed), and largest (year) to smallest (month).

If you had no leading zero for months, and/or for year, it wouldn't have worked, but in your case, >, >=, ==, <= and < should work.