When determining whether an object exists in a set of objects, consider using an NSSet
/NSMutableSet
object (or NSOrderedSet
/NSMutableOrderedSet
if you are developing for Mac OS X 10.7 or iOS 5.0 and want to retain the order of elements in the set). An NSSet
container is designed for efficient lookups. When an object has a decent hash
(which most Foundation objects do), the lookup is effectively O(1), which is faster than a binary search.
NSSet *dateSet = [NSSet setWithArray:dateArray];
if ([dateSet containsObject:date1])
{
// do something
}
Note that it is important to construct the set once rather than converting it from an array each time, or else you'll lose any performance benefit.
For more information, see here.
Since you are wanting to check for specified dates regardless of time, you need to truncate the date values before adding them to the set. For example (pick better names, this is only an example):
// potentially add as a category method to NSDate
- (NSDate *) dateByTruncatingTime
{
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:aDate];
return [[NSCalendar currentCalendar] dateFromComponents:components];
}
// ------------- somewhere else -------------
- (void) actionHappened
{
[myMutableSet addObject:[[NSDate date] dateByTruncatingTime]];
}
- (BOOL) didActionHappenOnDate:(NSDate *) aDate
{
return [myMutableSet containsObject:[aDate dateByTruncatingTime]];
}