Reputation: 5524
Lets say I have NSMutableArray of different dates. Dates are represented in UITableView. If I click on UITableViewCell, how do I get all dates of that same day from NSMutableArray ?
So lets say I have 3 dates inserted on monday, 1 on tuesday, 4 on wednesday and so on... If I press 1/3 dates that represent monday, how can I get all 3 dates that are monday and ignore other days??
And if possible, how can I sort them ?? So If I saved in 8, 9, 10 hours (all on monday) and I press any of hours (minutes are also included), they will be sorted 8-9-10 exactly how they really happened...
Tnx.
Upvotes: 1
Views: 461
Reputation: 3522
Date computation with NSDate and company is a bit complicated but actually quite powerful once you get the hang of it. Here is one way to filter your array:
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSMutableArray *dates = [NSMutableArray array];
NSDate *selectedDate = [NSDate date];
for (int i=0; i<70; i++)
[dates addObject:[NSDate dateWithTimeIntervalSinceNow:i * 60*60*24]];
NSInteger selectedDayOfWeek = [calendar components:NSWeekdayCalendarUnit fromDate:selectedDate].weekday;
NSPredicate *filter = [NSPredicate predicateWithBlock:^(id object, NSDictionary *bindings) {
return (BOOL)([calendar components:NSWeekdayCalendarUnit fromDate:object].weekday == selectedDayOfWeek);
}];
NSArray *filteredDates = [dates filteredArrayUsingPredicate:filter];
NSArray *sortedDates = [filteredArray sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"%@", filteredDates);
}
return 0;
}
Upvotes: 1