我是核心数据的新手,正在尝试弄清楚如何sectionNameKeyPath
在我的NSFetchedResultsController
. 我有一个托管对象,其属性名为acctPeriod
. 它是一个NSString
. 我想根据该字段的前 4 个字符创建部分。前4个字符代表会计期间的年份,不需要保存。
我浏览了这个站点并看到了有关瞬态属性的帖子,但我似乎无法让它们工作。基本上我想要这个,然后分配periodYear
给我的sectionNameKeyPath
.
@dynamic periodYear;
-(NSString *)periodYear
{
return [self.acctPeriod substringToIndex:4];
}
任何帮助,将不胜感激。
**更新:使用 Martin R. 的答案,我能够让它按预期工作。
- (NSFetchedResultsController *)fetchedResultsController
{
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Billing" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"acctPeriod" ascending:NO];
NSArray *sortDescriptors = @[sortDescriptor];
//Predicate
NSPredicate *pred = [NSPredicate predicateWithFormat:@"clients = %@", self.client];
NSLog(@"%@",pred);
//[fetchRequest setResultType:NSDictionaryResultType];
//[fetchRequest setReturnsDistinctResults:YES];
[fetchRequest setPredicate:pred];
[fetchRequest setSortDescriptors:sortDescriptors];
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"periodYear" cacheName:nil];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error])
{
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _fetchedResultsController;
}