I am working on a TV-guide app, and am trying to get the nearest 3 dates from an NSArray with NSDictionary’s. So far so good, but I have been trying to figure out how I can do this the best way using as little memory as possible and with as little code (hence decreasing the likelihood of bugs or crashes). The array is already sorted.
I have a dictionary with all the channels shows for one day. The dictionary withholds an NSDate (called date).
Lets say a channel has 8 shows and the time is now 11:45. show #3 started at 11:00 and ends at 12:00, show #4 starts at 12:00 and ends at 13:00, show #5 at 13:00 to 14:00 ect.
How could I fetch show #3 (which started in the past!), #4 and #5 the fastest (memory wise) and easiest from my array of dictionaries?
Currently I am doing a for loop fetching each dictionary, and then comparing the dictionaries date with the current date. And thats where I am stuck. Or maybe I just have a brain-fag.
My current code (after a while of testing different things):
- (NSArray*)getCommingProgramsFromDict:(NSArray*)programs amountOfShows:(int)shows
{
int fetched = 0;
NSMutableArray *resultArray = [[NSMutableArray alloc] init];
NSDate *latestDate = [NSDate date];
for (NSDictionary *program in programs)
{
NSDate *startDate = [program objectForKey:@"date"];
NSLog(@"Program: %@", program);
switch ([latestDate compare:startDate]) {
case NSOrderedAscending:
NSLog(@"latestDate is older, meaning the show starts in the future from latestDate");
// do something
break;
case NSOrderedSame:
NSLog(@"latestDate is the same as startDate");
// do something
break;
case NSOrderedDescending:
NSLog(@"latestDate is more recent, meaning show starts in the past");
// do something
break;
}
// Now what?
}
return resultArray;
}
I am writing it for iOS 5, using ARC.
After your EDIT and explanation, here is another answer, hopefully fitting your question better.
The idea is to find the index of the show that is next (startDate after now). Once you have it, it will be easy to get the show at the previous index (on air) and the 2 shows after it.
At that stage,
indexOfNextShowcontains the index of the show in yourNSArraythat will air after the current show. Thus what you want according to your question is objects at indexindexOfNextShow-1(show on air),indexOfNextShow(next show) andindexOfNextShow+1(show after the next).Obviously in practice you should add some verifications (like
indexOfNextShowbeing >0 before trying to access object at indexindexOfNextShow-1andindexOfNextShow+1not being past the total number of shows in your array).The advantage of this is that since your array of shows is sorted by startDate already,
indexOfObjectPassingTest:returns the first object passing the test, and stop iterating as soon as it has found the right object. So this is both concise, easy-to-read code and relatively efficient..