【发布时间】:2013-12-20 10:03:58
【问题描述】:
我将 NSDate 传递给以下函数,并希望在数组中找到与传入值最接近的 NSDate。
请注意,我不想知道数组是否包含像这篇文章这样的确切日期: Find NSDate in sorted NSArray
我想知道数组中哪个日期在时间上最接近我的参考日期。
我必须经常这样做。以下工作但速度很慢 - 我怎样才能加快速度?
// Get the XYZ data nearest to the passed time
- (eciXYZ)eciDataForTime:(NSDate*)time {
// Iterate our list and find the nearest time
float nearestTime = 86400; // Maximum size of dataset ( 2 days )
int index = 0; // Track the index
int smallestDifferenceIndex = index; // Track the index with the smallest index
NSDate *lastListDate; // Track the closest list date
for ( index = 0 ; index < [self.time count]-1 ; index++ ) {
NSDate *listDate = [self.time objectAtIndex:index]; // Get the date - Time is an NSMutableArray of NSDates
// NSTimeInterval is specified in seconds; it yields sub-millisecond precision over a range of 10,000 years.
NSTimeInterval timeDifferenceBetweenDates = [listDate timeIntervalSinceDate:time];
if ( timeDifferenceBetweenDates < nearestTime && timeDifferenceBetweenDates > 0 ) {
nearestTime = timeDifferenceBetweenDates; // Update the tracker
smallestDifferenceIndex = index; // Update the smallest difference tracker
lastListDate = listDate; // Capture the closest date match
//NSLog(@"Time: %f %@",timeDifferenceBetweenDates,listDate);
}
}
【问题讨论】:
标签: objective-c nsarray nsdate nstimeinterval