CoreData按即将到来的生日排序

时间:2010-12-06 21:13:26

标签: iphone cocoa-touch core-data nsfetchedresultscontroller

我正在xcode中构建我的第一个应用程序并尝试使用coreData和NSFetchedResultController获取即将到来的生日所订购的人员列表。我的实体设置如下

uBirthdays
--------------
NSString uName
NSDate uBday

这是我目前的代码:

- (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 setSortDescriptors:[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;    

}

是否有可能在即将到来的生日那天排序?或者我是否必须对我的生日进行去标准化,以便我可以按月分类?任何意见都非常感谢。

谢谢

1 个答案:

答案 0 :(得分:1)

这是你能做的。

1)为您的uBDay和uName设置NSSortDescriptors,这样您的记录将首先按生日排序,然后按名称排序。

2)创建一个NSPredicate,将[NSDate now](即今天)之间的所有生日拉到将来的某个特定时间(即未来30天= [NSDate dateWithTimeIntervalSinceNow:kOneDayTimeInterval*30]

以下示例代码:

#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];
        ...