Feta
Feta

Reputation: 532

Core data, search for objects based on objects own property

I have an NSManagedObject, foo that stores the NSDate it was created. It also has another field, lifespan which store how many seconds the object is valid for. Each foo can have a different lifespan value. Is it possible to return all foos who have not exceed their lifespan? I'm not sure how to express that in my NSPredicate or if it is even possible?

Upvotes: 1

Views: 117

Answers (2)

Martin R
Martin R

Reputation: 540145

A Core Data fetch request can actually contain simple arithmetic expression. So to find all objects where "created + lifespan >= now", the following works:

NSDate *now = [NSDate date];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"created + lifespan >= %@", now];

Upvotes: 2

Nicholas Hart
Nicholas Hart

Reputation: 1724

Yes, it is possible. eg:

NSDate * yesterday = [NSDate dateWithTimeIntervalSinceNow:-(60 * 60 * 24)];
NSPredicate * predicate = [[NSPredicate alloc] initWithFormat:@"dateCreated > %@", yesterday];
NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setPredicate:predicate];
NSError * error = nil;
NSArray * results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

Here is more info on writing predicates: http://developer.apple.com/library/ios/#DOCUMENTATION/Cocoa/Conceptual/Predicates/Articles/pCreating.html

Upvotes: 2

Related Questions