问题
here is an example to filter the array which has start time and end time according to the current time. this is working fine:
QUESTION : but here I want to know the index position of the collectionArr where predicate pick the value.
NSDate* currentDate = [NSDate date];
NSDateFormatter *_formatter = [[[NSDateFormatter alloc] init] autorelease];
[_formatter setLocale:[NSLocale currentLocale]];
[_formatter setDateFormat:@"yyyy-MM-dd hh:mm a"];
NSString *_date=[_formatter stringFromDate:currentDate];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"StartDate <= %@ AND EndDate = %@", _date, _date];
if (shortPrograms.count > 0) {
[shortPrograms removeAllObjects];
}
//collectionArr have multiple dictionaries ,which has start date and end date.
//collectionArr = [[NSArray alloc] initWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:@"..Sdate..",@"Startdate",@"..Edate..",@"Enddate", nil], nil];
//shortPrograms is a filter are, having the date in between start date and end date.
[shortPrograms addObjectsFromArray:[collectionArr filteredArrayUsingPredicate:predicate]];
回答1:
Your shortPrograms
array contains a subset of the objects from collectionArr
. It sounds like you want to get an object from shortPrograms
and determine where in collectionArr
it came from.
In general you can't. But if all of the objects in collectionArr
are unique then it is possible.
id someObject = shortPrograms[someIndex]; // get some value
NSUInteger originalIndex = [collectionArr indexOfObject:someObject];
If your objects in collectionArr
are not unique, then this won't work because there is no way to know which of the duplicates you are dealing with.
回答2:
If you want to get indexes from an array based on some comparison, you should use indexesOfObjectsPassingTest:, not a predicate. It appears that you want to find the indexes of objects whose end time is the same as the current date (which would include the time). This will only work, if the value for the key EndDate is an NSDate object, not a string. Also, assuming that your start dates are always the same or earlier then the end dates, there's no reason to check the start time, only the end. This is how you might use the method I mentioned above:
NSIndexSet *indxs = [collectionArr indexesOfObjectsPassingTest:^BOOL(NSDictionary *dict, NSUInteger idx, BOOL *stop) {
return (fabs([dict[@"EndDate"] timeIntervalSinceNow]) < 10);
}];
NSLog(@"%@",indxs);
This would return the indexes of any dictionaries where the value for the key EndDate was less then 10 seconds away from the current time and date.
回答3:
From my little knowledge, its not possible with NSPredicate
There is no method available in NSPredicate
which will return the index position.
You may have to implement your own logic to achieve your goal.
来源:https://stackoverflow.com/questions/15667615/how-to-find-the-index-position-of-the-array-where-nspredicate-pick-the-value-i