Do this:
Dump the array of NSDates and keep an array of NSStrings instead.
NSArray* busTimes = @[@"06:40:00", @"07:50:00", ...];
NSDateFormatter* fmtr = [[NSDateFormatter alloc] init];
[fmtr setFormat:@"HH:mm:ss"];
NSDate nowDate = [NSDate date];
NSString* nowString = [fmtr stringFromDate:nowDate];
NSString* closestTime = nil;
for (NSString* busTime in busTimes) {
if ([busTime compare:nowString] == NSOrderedDescending ) {
closestTime = busTime;
break;
}
}
(Note that I haven't changed the logic in loop, which appears a bit suspicious, depending on whether you assume the data is ordered or not.)
Another way to do it:
NSArray* busTimes = @[@"06:40:00", @"07:50:00", ...];
NSDateFormatter* fmtr = [[NSDateFormatter alloc] init];
[fmtr setFormat:@"HH:mm:ss"];
NSMutableArray* busMinutes = [NSMutableArray array];
for (NSString* time in busTimes) {
NSTimeInterval doubleTime = [[fmtr dateFromString:time] timeIntervalSinceReferenceDate];
[busMinutes addObject: [NSNumber numberWithDouble:doubleTime]];
}
NSDate* nowDate = [NSDate date];
NSString* nowString = [fmtr stringFromDate:nowDate];
NSDate* nowDate2 = [fmtr dateFromString:nowString];
NSTimeInterval nowInterval = [nowDate2 timeIntervalSinceReferenceDate];
double closestTime = 0.0;
double secondsDifference = -99.0;
for (NSNumber* busMinute in busMinutes) {
double busInterval = [busMinutes doubleValue];
if (busInterval > nowInterval) {
closestTime = busInterval;
secondsDifference = busInterval - nowInterval;
}
}
(Of course, you can't use the above scheme until you can explain what it does.)