Ios 如何找到NSPredicate拾取值的数组的索引位置。我使用FilteredarrayingPredicate作为过滤器

Ios 如何找到NSPredicate拾取值的数组的索引位置。我使用FilteredarrayingPredicate作为过滤器,ios,objective-c,nspredicate,Ios,Objective C,Nspredicate,下面是一个根据当前时间筛选具有开始时间和结束时间的数组的示例。这很好: 问题:但这里我想知道收集器的索引位置,谓词在其中选择值。 NSDate* currentDate = [NSDate date]; NSDateFormatter *_formatter = [[[NSDateFormatter alloc] init] autorelease]; [_formatter setLocale:[NSLocale currentLocale]]; [_formatter setDateForm

下面是一个根据当前时间筛选具有开始时间和结束时间的数组的示例。这很好:

问题:但这里我想知道收集器的索引位置,谓词在其中选择值。

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]];
NSDate*currentDate=[NSDate日期];
NSDateFormatter*(格式化程序=[[NSDateFormatter alloc]init]autorelease];
[_格式化程序setLocale:[NSLocale currentLocale]];
[_格式化程序setDateFormat:@“yyyy-MM-dd hh:MM-a”];
NSString*\u date=[\u格式化程序stringFromDate:currentDate];

NSPredicate*谓词=[NSPredicate predicate ewithformat:@“StartDate据我所知,使用
NSPredicate

NSPredicate
中没有可返回索引位置的方法


您可能需要实现自己的逻辑才能实现目标。

您的
shortPrograms
数组包含来自
collectionArr
的对象子集。听起来您想从
shortPrograms
获取对象,并确定它来自
collectionArr
的位置

通常不能。但是如果
collectionar
中的所有对象都是唯一的,那么这是可能的

id someObject = shortPrograms[someIndex]; // get some value
NSUInteger originalIndex = [collectionArr indexOfObject:someObject];

如果您在
collectionArr
中的对象不是唯一的,那么这将不起作用,因为无法知道您正在处理哪些重复项。

如果您希望根据比较从数组中获取索引,则应使用indexesOfObjectsPassingTest:,而不是谓词。您似乎想要查找ob的索引结束时间与当前日期(包括时间)相同的对象。这仅在键EndDate的值是NSDate对象而不是字符串的情况下才有效。此外,假设开始日期始终与结束日期相同或更早,则没有理由检查开始时间,只检查结束时间。这就是我上面提到的方法的用法:

NSIndexSet *indxs = [collectionArr indexesOfObjectsPassingTest:^BOOL(NSDictionary *dict, NSUInteger idx, BOOL *stop) {
        return (fabs([dict[@"EndDate"] timeIntervalSinceNow]) < 10);
    }];
NSLog(@"%@",indxs);
NSIndexSet*indxs=[collectionarindexesofobjectspassingtest:^BOOL(NSDictionary*dict,NSUInteger idx,BOOL*stop){
返回(fabs([dict[@“EndDate”]timeIntervalSinceNow])<10);
}];
NSLog(@“%@”,indxs);

这将返回任何字典的索引,其中键EndDate的值与当前时间和日期的距离小于10秒。

您无法通过这种方式比较日期字符串,您必须比较NSDate对象。您的数组似乎正在存储日期字符串,是真的吗?我需要计算NSDate,但我不知道是否可以提取nsdate对象与nsstring相同。这里我将nsdate转换为nsstring,请建议我。我不明白您需要获取nsdate是什么意思。您从哪里获取?您是否在某处存储了nsdate对象?