如何使用核心数据中的NSPredicate从其中一个属性获取值

时间:2013-03-30 15:23:58

标签: iphone ios core-data nspredicate

我有一个基于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]];

1 个答案:

答案 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;