我有一个基于Core Data的项目。其中一个属性称为“日期”,我想从该属性中获取值,值以字符串“2013-03”开始,但我只能得到最新值,例如字符串“2013-03-30”,如何将所有值以“2013-03”开头到NSArray中?
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Database" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"date beginsWith %@",value];
[fetchRequest setPredicate:predicate];
NSSortDescriptor *sortDescription = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
[fetchRequest setSortDescriptors:@[sortDescription]];
答案 0 :(得分:2)
我自己解决了这个问题 NSMutableArray * array = [[NSMutableArray alloc] init];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Database" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"date beginsWith %@",value];
[fetchRequest setPredicate:predicate];
NSSortDescriptor *sortDescription = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
[fetchRequest setSortDescriptors:@[sortDescription]];
NSError *fetchError = nil;
NSArray *fetchArray = [self.managedObjectContext executeFetchRequest:fetchRequest error:&fetchError];
if ([fetchArray count] > 0)
{
for (Database *fetchResult in fetchArray)
{
[array addObject:fetchResult.date];
}
}
return array;