问题
I have a Person
object. and this person
object has the following attributes;
Name
StartDate
EndDate
I am saving this Person
objects to an array
. This array might contain more than 100 person
objects.
The following is an example of person
objects in that array;
John, Tue Feb 22, Thr Mar 30
Jack, Wed Mar 09, Fri Apr 21
Jack, Thu Mar 19, Fri Dec 20
Jack, Tue Jan 08, Fri Apr 26 etc..
Now i need to will supply a date, say for example Wed 29 Mar
, and i need to check if it's in the range of StartDate
and EndDate
in the array of persons
object. How can i do this ? My working are as follows, but it doesn't work (It gives incorrect results)
NSPredicate *datePred = [NSPredicate predicateWithFormat:@"StartDate>= %@ && EndDate<= %@",givenDate,givenDate];
resultArray = [arrayContainingAllPersonObjects filteredArrayUsingPredicate:datePred ];
I also tried the following method, but it too gives incorrect results (which was taken off a SO post);
NSPredicate *greaterThanPredicate = [NSPredicate predicateWithFormat:@"StartDate<= %@", providedDate"];
NSPredicate *lessThanPredicate = [NSPredicate predicateWithFormat:@"EndDate>= %@", ProvidedDate"];
NSPredicate *betweenPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:greaterThanPredicate, lessThanPredicate, nil]];
I have no clue as in what is causing this, Help
回答1:
Are the StartDate and EndDate NSDate objects?
I'd suggest giving this writeup about predicates a look. It has helped me reduce my filtering and searching code to a few lines: http://www.cocoanetics.com/2010/03/filtering-fun-with-predicates/
回答2:
Try using '%@' like StartDate = '%@' && EndDate ='%@'
UPD:
Try
NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"StartDate = '%@', startDateHere]];
来源:https://stackoverflow.com/questions/10307902/writing-a-simple-nspredicate-logic-issue