在已排序的 NSArray 中查找 NSDate [英] Find NSDate in sorted NSArray

查看:46
本文介绍了在已排序的 NSArray 中查找 NSDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 NSDate 对象的排序数组.我想要做的是创建一个方法,该方法接受一个日期并返回 YES 或 NO,具体取决于该日期是否可以在日期数组中找到.

I have a sorted array of NSDate objects. What I'd like to do is create a method that takes in a date and returns YES or NO depending on whether that date can be found in the date array.

NSArray *dateArray;

-(BOOL)arrayContainsDate(NSDate *)d {
  // return YES if d is found in dateArray
}

我知道如何通过逐个遍历数组的每个元素来完成此操作,但我需要一种更快的方法.

I know how to do this by going through each element of the array one by one, but I need a quicker way.

推荐答案

在确定某个对象是否存在于一组对象中时,请考虑使用 NSSet/NSMutableSet 对象(或 NSOrderedSet/NSMutableOrderedSet 如果您正在开发r Mac OS X 10.7 或 iOS 5.0 并希望保留集合中元素的顺序).NSSet 容器是为高效查找而设计的.当一个对象有一个合适的 hash(大多数 Foundation 对象都这样做)时,查找实际上是 O(1),这比二分查找要快.

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]];
}

这篇关于在已排序的 NSArray 中查找 NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆