I feel like this is simple but I just can't wrap my head around it. I have an array of days of the week that a user can select against:
NSArray * daysOfTheWeek = [NSArray arrayWithObjects:@"sunday", @"monday", @"tuesday", @"wednesday", @"thursday", @"friday", @"saturday", nil];
I as the toggle the days on and off, I'd like to sort their NSArray fo selected days against the dayOfTheWeek
NSArray. So if a user has:
NSArray * userDays = [NSArray arrayWithObjects:@"thursday", @"monday", @"friday"];
I want to sort this so that its monday, thursday, friday.
I'd seem some of the similar questions posted but none were clear enough for me to know how I could apply them to this. Could be my lack of sleep :)
Thank you!
NSArray *sortedUserDays = [userDays sortedArrayUsingComparator:^(id a, id b) {
return [@([daysOfTheWeek indexOfObject:a]) compare:@([daysOfTheWeek indexOfObject:b])];
}];
Edit: This sorts the array using a block as a comparator.
To compare two elements of the userDays
array it first searches their positions in the template array daysOfTheWeek
: [daysOfTheWeek indexOfObject:a]
It then wraps the positions into NSNumbers: @(index)
.
Next it calls compare:
on the wrapped indices. That's just a lazy way of returning an NSComparisonResult
for the two NSUInteger
positions.
另一种方法是使用用户选项简单地过滤一周中的几天。
NSArray *sortedUserDays = [daysOfTheWeek filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF in (%@)", userDays]];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.