我的app.Am使用coredata将截止日期NSStrings
存储在coredata中。现在我处于检索两个日期之间的记录的情况。(我的截止日期以ex:29/8/14的格式存储)如果我想要检索之间的记录,例如:29/8/14到28 / 10月14日,如何实现这一目标?有可能吗?
我插入记录的代码是
-(void)insertBill:(NSMutableDictionary *)bill
{
Bill *info = nil;
info = [self getBills:bill];
if(info!=nil) {
NSLog(@"Bill already Exists");
}
else
{////NSLog(@"adding new");
if(info==nil)
info = [NSEntityDescription
insertNewObjectForEntityForName:@"Bill"
inManagedObjectContext:self.managedObjectContext];
[info setValue:[bill valueForKey:@"billId"] forKey:@"billId"];
[info setValue:[bill valueForKey:@"category"] forKey:@"category"];
[info setValue:[bill valueForKey:@"billName"] forKey:@"billName"];
[info setValue:[bill valueForKey:@"account"] forKey:@"account"];
[info setValue:[bill valueForKey:@"amount"] forKey:@"amount"];
[info setValue:[bill valueForKey:@"recurring"] forKey:@"recurring"];
[info setValue:[bill valueForKey:@"dueDate"] forKey:@"dueDate"];
[info setValue:[bill valueForKey:@"reminder"] forKey:@"reminder"];
[info setValue:[bill valueForKey:@"dailyReminder"] forKey:@"dailyReminder"];
[info setValue:[bill valueForKey:@"time"] forKey:@"time"];
[info setValue:[bill valueForKey:@"notes"] forKey:@"notes"];
[info setValue:[bill valueForKey:@"imagePath"] forKey:@"imagePath"];
[info setValue:[bill valueForKey:@"recurringPeriod"] forKey:@"recurringPeriod"];
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
else
{
NSLog(@"Saved Successfully");
}
}
}
和getBills方法检查重复
- (Bill *)getBills:(NSMutableDictionary *)data
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Bill" inManagedObjectContext:self.managedObjectContext];
if([data valueForKey:@"billId"])
{
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"(billId == %@)", [data objectForKey:@"billId"]]];
}
NSError *error;
[fetchRequest setEntity:entity];
NSArray* dataa = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if(dataa.count>0)
return [dataa objectAtIndex:0];
else
return nil;
}
请给我一个解决方案。请告诉我在这种情况下我们可以将NSDate存储为NSString吗?否则是否需要将'duedate'的数据类型更改为NSDate? 请帮助我。有任何帮助,我们将不胜感激。
答案 0 :(得分:0)
好的,您可以将NSDate存储为字符串。
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
NSString *dateString = [dateFormat stringFromDate:yourNSDate];
但是,最好以NSDate格式存储日期,而不是将其存储为字符串。 NSDate只是一个大整数,表示很久以前经过的秒数。因此,如果您将数据类型更改为NSDate,则更容易编写谓词,从而提供更好的灵活性。
这是一个例子
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"billId == %@ && (dueDate >= %@ && dueDate <= %@", [data objectForKey:@"billId"],fromDate,toDate]];
这里注意fromDate和toDate是两个NSDate实例。