根据技术人员列表的大小,循环将起作用。下面的代码遍历列表,将每个项目分成三部分(日期、时间、技术人员),计算从现在开始的时间间隔并确定哪个是最近/活动的代理(时间间隔应该是最大的负数)。
为了得到一些有意义的东西,我改变了数组中的日期。
NSArray *agents = [NSArray arrayWithObjects:
@"20130920;0800;John Doe",
@"20130920;1400;Sally Smith",
@"20130920;2000;Jim Jones",
@"20130921;0800;Jane Johnson",nil];
// Setup date formatter
NSDateFormatter* onCallFormatter = [[[NSDateFormatter alloc] init] autorelease];
[onCallFormatter setDateFormat:@"yyyyMMddHHmm"];
[onCallFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
NSTimeInterval mostRecent = -9999999999999;
NSInteger agentIndex;
int i;
for ( i=0; i < [agents count]; i++ ) {
// Split string into elements
NSArray *elements = [[agents objectAtIndex:i] componentsSeparatedByString:@";"];
// Convert date/time into NSDate
NSDate *onCallDateTime = [onCallFormatter dateFromString:[NSString stringWithFormat:@"%@%@", elements[0], elements[1]]];
// Calculate the time interval against current date/time
NSTimeInterval onCallInterval = [onCallDateTime timeIntervalSinceNow];
// The agent on call would be the one with the largest negative interval
// onCallInterval should be < 0 (postive would be in the future)
if ( mostRecent < onCallInterval && onCallInterval < 0) {
mostRecent = onCallInterval;
agentIndex = i;
}
NSLog( @"%@ on call since %@ - %@ - %f hrs ", elements[2], elements[0], elements[1], onCallInterval/(60*60) );
}
NSLog( @"On call = %@", [agents objectAtIndex:agentIndex] );