2

I had a project based on Core Data.And one of the Attributes there is called "date",I want to get values from that attribute,and values beginsWith the string "2013-03",but I can only get the latest value ,such as string "2013-03-30", How can I get all values begin with "2013-03" into 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]];
4

1 回答 1

2

I work it out by myself 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;
于 2013-03-30T15:46:16.260 回答