我有这种过滤我的数据的逻辑(一个字典数组,其中字典有一些日期键和值)。我觉得这不是一个使用循环的好方法。
我需要一些关键的想法,以便我可以增强这个解决方案& make很快。
-(NSArray *)getCurrentShiftData {
NSMutableArray *returnArray = [[NSMutableArray alloc]init];
NSArray *tempArray = [[self dataStore] valueForKeyPath:key_RootKey];
for(NSDictionary *dict in tempArray) {
NSDateFormatter *empDateFormatter = [[NSDateFormatter alloc]init];
[empDateFormatter setDateFormat:@"yyyy/M/d H:m"];
NSString *dt = [dict valueForKey:key_StartDate];
NSDate *empDate = [empDateFormatter dateFromString:dt];
[empDateFormatter setDateFormat:@"yyyy/M/d"];
NSString *compareDate = [empDateFormatter stringFromDate:empDate];
NSDateFormatter *currentDateFormatter = [[NSDateFormatter alloc]init];
[currentDateFormatter setDateFormat:@"yyyy/M/d"];
NSString *today = [currentDateFormatter stringFromDate:[NSDate date]];
if([today isEqualToString:comapreDate]) {
[returnArray addObject:dict];
}
}
return ([returnArray count]) ? (NSArray*)returnArray : @[];
}
答案 0 :(得分:3)
试试这个:
-(NSArray *)getCurrentShiftData
{
NSMutableArray *returnArray = [NSMutableArray array];
NSArray *tempArray = [self.dataStore valueForKeyPath:key_RootKey];
NSDateFormatter *empDateFormatter = [[NSDateFormatter alloc]init];
[empDateFormatter setDateFormat:@"yyyy/M/d H:m"];
NSDateFormatter *currentDateFormatter = [[NSDateFormatter alloc]init];
[currentDateFormatter setDateFormat:@"yyyy/M/d"];
NSString *today = [currentDateFormatter stringFromDate:[NSDate date]];
for(NSDictionary *dict in tempArray)
{
NSString *dt = [dict valueForKey:key_StartDate];
NSDate *empDate = [empDateFormatter dateFromString:dt];
[empDateFormatter setDateFormat:@"yyyy/M/d"];
NSString *compareDate = [empDateFormatter stringFromDate:empDate];
if([today isEqualToString:compareDate])
{
[returnArray addObject:dict];
}
}
return (NSArray*)returnArray;
}
答案 1 :(得分:2)
在您有理由和证明(来自分析)性能问题的来源之前,不要担心速度。
那说:
最后一点 - 分析
答案 2 :(得分:1)
试试这个,希望它可以帮到你。
NSArray *tempArray= [[self dataStore] valueForKeyPath:key_RootKey];
NSDateFormatter *empDateFormatter = [[NSDateFormatter alloc] init];
NSDate *referenceDate = [NSDate date];
[empDateFormatter setDateFormat:@"yyyy/M/d H:m"];
NSDate *todayDate = [empDateFormatter dateFromString:[empDateFormatter stringFromDate:referenceDate]];
[empDateFormatter setDateFormat:@"yyyy/M/d H:m"];
NSPredicate *findDates = [NSPredicate predicateWithBlock: ^BOOL(id obj, NSDictionary *bind){
if (([todayDate compare:[empDateFormatter dateFromString:[obj valueForKey:key_StartDate]]]==NSOrderedSame)) {
return YES;
}
return NO;
}];
NSArray *matchedRecords = [tempArray filteredArrayUsingPredicate:findDates];
答案 3 :(得分:0)
使用NSPredicate
NSString *predicateStr = [NSString stringWithFormat:@"%@ == '%@'", key, value];
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateStr];
NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];