目前正致力于寻找最佳解决方案,以找到当前时间和我的数组内部的日期之间的最小时间间隔。寻找最小的时间间隔(现在和阵列之间的日期)
我有一个方法,需要一个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;
}
我如何能清理这件事有什么建议?
如果你的数组进行排序,使用二进制搜索。 –