嗨,我是这个coredata的新手.我有两个实体CategoryList和ExpenseList.CategoryList包含两个属性
1.dates(nsdate)
2.categories(nsstring)
以及与ExpenseList的多个关系,关系名称为"expenseList"ExpenseList由1.amountSpent(float)组成.
我只是想知道了解coredata中的关系特征.当我试图创建一个nspredicate来按特定日期过滤数据时,它什么也没有返回.我只想过滤CategoryList实体中的类别属性内容以获取特定日期.这是我的代码
-(void) callingByDate
{
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSEntityDescription *categoryL = [NSEntityDescription entityForName:@"CategoryList" inManagedObjectContext:managedObjectContext];
NSSortDescriptor *dateSort = [[NSSortDescriptor alloc]initWithKey:@"date" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:dateSort, nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"dates == %@",date];
NSFetchRequest *dateFetch = [[NSFetchRequest alloc]init];
[dateFetch setSortDescriptors:sortDescriptors];
[dateFetch setEntity:categoryL];
[dateFetch setPredicate:predicate];
NSMutableArray *results = [[managedObjectContext executeFetchRequest:dateFetch error:nil] mutableCopy];
if([results count] > 0)
NSLog(@"results found");
else
NSLog(@"no results found");
}
Run Code Online (Sandbox Code Playgroud)
当我在nslog区域执行此代码时,它显示"找不到结果".我无法弄清楚为什么.提前致谢
这是我的代码,以找到一天的结束和开始
-(NSDate *)beginningOfDay:(NSDate *)date;
{
NSDate *dat = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:( NSMonthCalendarUnit | NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:dat];
[components setHour:0];
[components setMinute:0];
[components setSecond:0];
return [cal dateFromComponents:components];
}
-(NSDate *)endOfDay:(NSDate *)date;
{
NSDate *dat = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:( NSMonthCalendarUnit | NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:dat];
[components setHour:23];
[components setMinute:59];
[components setSecond:59];
return [cal dateFromComponents:components];
Run Code Online (Sandbox Code Playgroud)
当我的nslog,结果显示是开始日-2013-04-30 18:30:00 +0000 endOfDay -2013-05-01 18:29:59 +0000
date实际上是一个时间戳,所以==使用它只会返回具有确切时间戳的项目.
要获取特定日期的所有条目,您需要获取NSDate一天的开始(startOfDay)和NSDate一天的结束(endOfDay)然后修改谓词以使用以下内容获取这两个值之间的日期:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"dates >= %@ AND dates >= %@", startOfDay, endOfDay];
Run Code Online (Sandbox Code Playgroud)
要计算startOfDay,endOfDay您可以手动自己完成,也可以使用其他库来计算它,例如https://github.com/erica/NSDate-Extensions.
| 归档时间: |
|
| 查看次数: |
4840 次 |
| 最近记录: |