Returning different dates from CoreData objects using NSPredicate

Hello

If I have this array:

var objects = [
    Object(value: 100, date: Date(), imageTemplate: "30"),
    Object(value: 200, date: Date(), imageTemplate: "20"),
    Object(value: 400, date: Date() + 84000, imageTemplate: "10")
]

How can I count how many different dates are in the array using NSPredicate?

In this case it should return 2.

Thank You!

Why do you absolutely want to use predicate ?

I tried this

struct Object {    // That's my guess of what Object is
    var value: Int
    var date: Date
    var imageTemplate: String
}

var objects = [
    Object(value: 100, date: Date(), imageTemplate: "30"),
    Object(value: 200, date: Date(), imageTemplate: "20"),
    Object(value: 400, date: Date() + 84000, imageTemplate: "10")
]

let dateObjects = objects.map() { $0.date.description }
let setObjects = Set(dateObjects)
print("Count", setObjects.count)

I get 2

Why do you absolutely want to use predicate ?

Because I Want to use it in @FetchRequest

On a side note, you shouldn't rely on separate calls to Date() returning the same value!
Date returns millisecond precision, so consecutive calls to Date() might return the same value (they probably will?), but they might not.

Better to say:

let dateNow = Date()
var objects = [
    Object(value: 100, date: dateNow, imageTemplate: "30"),
    Object(value: 200, date: dateNow, imageTemplate: "20"),
    Object(value: 400, date: dateNow + 84000, imageTemplate: "10")
]

it should return 2 You may be mistaking. The type Date contains sub-second info in it. The first Date() and the second may return different values. Generally NSPredicate is not a tool for counting, and working with actual date (year-month-day) with the type Date would be complex.

Ok Thank You

You want to do something like make the NSFetchRequest return NSDictionaryResultType or NSCountResultType with an NSExpressionDescription instead of a normal attribute name.

See expressionForFunction which accepts the "count:" function

Returning different dates from CoreData objects using NSPredicate
 
 
Q