Reputation: 313
I am currently working with core data to store meals. My entities are date (Date), foods (string) and drinks (string). Now I want to extract all the foods stored for the last seven days. How would I do this? I know i should somehow use NSPredicate, but I can't figure out how exactly.
Upvotes: 3
Views: 871
Reputation: 285290
Get the current calendar
let calendar = NSCalendar.currentCalendar()
Get the current date
let now = NSDate()
Subtract 7 days from current date
let sevenDaysAgo = calendar.dateByAddingUnit(.Day, value: -7, toDate: now, options: [])!
Get the start of the day 7 days ago
let startDate = calendar.startOfDayForDate(sevenDaysAgo)
Create the predicate, literal date
is the Core Data attribute
let predicate = NSPredicate(format:"(date >= %@) AND (date < %@)", startDate, now)
Upvotes: 4