I'm building my first app in xcode and trying to fetch a list of people ordered by upcoming birthdays using coreData and NSFetchedResultController. My entity is setup as follows
uBirthdays
--------------
NSString uName
NSDate uBday
Here is my current code:
- (NSFetchedResultsController *)fetchedResultsController {
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"uBirthdays" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"uBday" ascending:YES];
[fetchRequest setSortD开发者_开发问答escriptors:[NSArray arrayWithObject:sort]];
[fetchRequest setFetchBatchSize:20];
NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:@"sectionNameGen" cacheName:@"Root"];
self.fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;
[sort release];
[fetchRequest release];
[theFetchedResultsController release];
return _fetchedResultsController;
}
Is it possibly to sort that by upcoming birthdays? or would I have to de-normalize my birthdays so I can sort by month and day only? Any input is greatly appreciated.
Thank you
Here's what you can do.
1) Set NSSortDescriptors
for your uBDay and uName so your records will be sorted first by birthday, then by name.
2) Create a NSPredicate
that pulls all birthdays between [NSDate now]
(i.e. today) up to a certain time in the future (i.e. 30 days into the future = [NSDate dateWithTimeIntervalSinceNow:kOneDayTimeInterval*30]
)
Example code below:
#define kOneDayTimeInterval 86400 // this is in seconds: 86400 = 1 day
- (NSFetchedResultsController *)fetchedResultsController {
...
NSSortDescriptor *sortByBDay = [[NSSortDescriptor alloc] initWithKey:@"uBday" ascending:YES];
NSSortDescriptor *sortByName = [[NSSortDescriptor alloc] initWithKey:@"uName" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortByBDay,sortByName, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortByName release];
[sortByReleaseDate release];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(uBDay > %@) AND (uBDay <= %@)", [NSDate date], [NSDate dateWithTimeIntervalSinceNow:kOneDayTimeInterval*30]];
[fetchRequest setPredicate:predicate];
...
精彩评论