Core Data and fetch with predicate variable

0

I make a request to one of the entities of Core Data , but to do a calculation, I have to filter the results for which they meet two conditions:

  • That one of its attributes (bool), be true .
  • That another of its attributes (date), is between the 16th of the previous month and the 15th day of the current month.

Example:

func setDiasTMAnt() -> Int{
    if let context = context{
        let request : NSFetchRequest<Gastos> = Gastos.fetchRequest()
        let sortByDate = NSSortDescriptor(key: "date", ascending: false)
        let predicate = NSPredicate(format: "dayTM == true")
        request.sortDescriptors = [sortByDate]
        request.predicate = predicate
        do{
            let fetchedDayTM = try context.fetch(request)
            self.diasTM = fetchedDayTM
        }catch{
            print("Error al definir los días de TM en el mes anterior")
        }
        return diasTM.count
    }else{
        return 0
    }
}

I want both conditions to be met at the same time.

    
asked by Nacho.Casas 13.03.2017 в 13:15
source

1 answer

1

Create the two predicates:

let datePredicate = NSPredicate(format: "(date >= %@) AND (date <= %@)", startDate, endDate)

let booleanPredicate = NSPredicate(format: "dayTM == true")

And add them to an NSCompoundPredicate:

let andPredicate = NSCompoundPredicate(type:NSCompoundPredicateType.AndPredicateType, subpredicates:[datePredicate, booleanPredicate])

Finally add the NSCompoundPredicate as you preach:

request.predicate = andPredicate

I hope it helps you;)

    
answered by 14.03.2017 в 12:54