0

I'm creating a timeclock application where there is a ClockPunch NSManagedObject model with properties representing a clockin and clockout punch. Each ClockPunch instance has a relationship with an Employee in the Employees model (which also has a one-to-many relationship with each punch). I want to be able to write an NSPredicate that will give me the employee with their most recent clockin punch. I can then determine if they are clockedin or clocked out by whether or not they have a clockout punch to match. I do not want to pull all the punches in and then sort them, cause there could be 1000's for each employee. What should I do?

My Model looks like this

Employees<->>ClockPunches
tshepang
  • 12,111
  • 21
  • 91
  • 136
tslater
  • 4,362
  • 3
  • 23
  • 27

1 Answers1

0

I tried something very similar recently like this. I tried finding the registration with the maximum date.

NSFetchRequest* request = [Registration fetchRequest];
NSExpression *date = [NSExpression expressionForKeyPath:@"time"];

NSExpression *maxDate = [NSExpression expressionForFunction:@"max:"
                                                  arguments:[NSArray arrayWithObject:date]];

NSExpressionDescription *d = [[[NSExpressionDescription alloc] init] autorelease];
[d setName:@"maxTime"];
[d setExpression:maxDate];
[d setExpressionResultType:NSDateAttributeType];
[request setPropertiesToFetch:[NSArray arrayWithObject:d]];

NSError *error = nil;
NSArray *objects = [Registration executeFetchRequest:request];
if (objects == nil) {
    // Handle the error.
} else {
    if (0 < [objects count]) {
        NSLog(@"Maximum date: %@", [[objects objectAtIndex:0] valueForKey:@"type"]);
    }
}

You can find more details on this page. https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdFetching.html

However the part that I'm still missing is how to only look into the registrations of a specific employee... I tried combining the request setting an NSPredicate but somehow they can't be used together.

NOTE: I'm using restkit for my coredata access, follow the link to get a pure core data example (only small part of code is different)

Jeroen Coupé
  • 1,394
  • 11
  • 13
  • There are some good ideas in here. Unfortunately I need to get the most recent clock in and clock out times for each employee. Looks like we are in a similar boat :'-(... – tslater Sep 07 '12 at 21:55