I'm having a lot of problems with my code that determines the earliest date and latest date in an array. Here is the code I'm using:
NSDate *startDate = nil; // Earliest date
NSDate *endDate = nil; // Latest date
for (id entry in myArray)
{
NSDate *date = [entry objectForKey:kDate];
if (startDate == nil && endDate == nil)
{
startDate = date;
endDate = date;
}
else if ([date compare:endDate] == NSOrderedAscending)
{
startDate = date;
}
else if ([date compare:startDate] == NSOrderedDescending)
{
endDate = date;
}
date = nil;
}
Please can someone help me work out where I'm going wrong?
Surely you're setting startDate
and endDate
the wrong way round in the else if
statements? Don't you want this:
NSDate *startDate = nil; // Earliest date
NSDate *endDate = nil; // Latest date
for (id entry in myArray)
{
NSDate *date = [entry objectForKey:kDate];
if (startDate == nil && endDate == nil)
{
startDate = date;
endDate = date;
}
if ([date compare:startDate] == NSOrderedAscending)
{
startDate = date;
}
if ([date compare:endDate] == NSOrderedDescending)
{
endDate = date;
}
date = nil;
}