【发布时间】:2014-01-23 04:10:13
【问题描述】:
目前正在寻找最佳解决方案,以找到当前时间和我的数组中的日期之间的最小时间间隔。
我有一个接受 NSArray 并返回 NSArray 的方法。该方法执行以下操作:
- 循环遍历按时间排序的数组(
0索引最接近当前时间) - 通过查找增量和比较来查找最小区间
- 获取该索引,获取它,返回一个字典
我开始考虑使用timeIntervalSinceDate 等代替我在下面使用的手动工作。
数组看起来像这样:
tideSummary: [{
'type' : 'High Tide',
'pretty' : 'January 16 at 5:13PM EST',
'epoch' : '325267782',
...
}]
这段代码是否因为它试图做的事情而显得臃肿?我觉得根据索引和键值提取某些数据存在大量重复?
我想从数组中返回最近的时间,所以我想使用timeIntervalSince1970 并做一些简单的数学运算来找到最小的增量。我的数组包含一个以毫秒为单位返回时间的键
关于如何清理条件以便我仍然可以提取的任何建议:lowTideTime - highTideTime 和 tideType
以下是我用来提取此信息的方法:
- (NSArray *)findUpcomingTides: (NSArray *)arrayOfTideCycles {
NSTimeInterval currentDateInterval;
currentDateInterval = [[NSDate date]timeIntervalSince1970];
NSInteger smallestDelta = currentDateInterval;
NSArray *upcomingTideData = [[NSArray alloc] init];
for (NSInteger i = 0; i < arrayOfTideCycles.count; i++) {
NSDictionary *eachTideSummary = [arrayOfTideCycles objectAtIndex:i];
NSInteger tideDateAsEPOCH = [[eachTideSummary valueForKeyPath:@"epoch"] intValue];
NSInteger dateDelta = tideDateAsEPOCH - smallestDelta;
if (dateDelta < smallestDelta) {
smallestDelta = dateDelta;
int iPlusOne = i+1;
upcomingTide = [arrayOfTideCycles objectAtIndex:i];
NSDictionary *tideTypeDictionary = [arrayOfTideCycles objectAtIndex:i];
tideType = [tideTypeDictionary objectForKey:@"type"];
if([[upcomingTide valueForKeyPath:@"type"] isEqualToString:@"Low Tide"] || [[upcomingTide valueForKeyPath:@"type"] isEqualToString:@"Max Ebb"]){
NSString *lowTidePrettyDateFormat = [upcomingTide valueForKeyPath:@"pretty"];
lowTideTime = [self convertAndFormatDateToTimeWithString:lowTidePrettyDateFormat];
NSDictionary *upcomingHighTide = [arrayOfTideCycles objectAtIndex:iPlusOne];
NSString *highTidePrettyDateFormat = [upcomingHighTide valueForKeyPath:@"pretty"];
highTideTime = [self convertAndFormatDateToTimeWithString:highTidePrettyDateFormat];
} else {
NSString *highTidePrettyDateFormat = [upcomingTide valueForKeyPath:@"pretty"];
highTideTime = [self convertAndFormatDateToTimeWithString:highTidePrettyDateFormat];
NSDictionary *upcomingLowTide = [arrayOfTideCycles objectAtIndex:iPlusOne];
NSString *lowTidePrettyDateFormat = [upcomingLowTide valueForKeyPath:@"pretty"];
lowTideTime = [self convertAndFormatDateToTimeWithString:lowTidePrettyDateFormat];
}
upcomingTideData = [NSArray arrayWithObjects:lowTideTime, highTideTime, tideType, nil];
}
}
return upcomingTideData;
}
关于如何清理这个有什么建议吗?
【问题讨论】:
-
如果您的数组已排序,请使用二进制搜索。
标签: ios objective-c arrays