我的数据模型中有两个对象...
- 人{姓名、职位、职务}
- 位置{position, PositionSort}
以上每一个都有自己的类文件(NSManagedObject 的子类)。我正在尝试按上面的 PositionSort 进行排序。我目前可以使用以下代码按位置排序。
NSSortDescriptor *sortDescriptorPosition = [[NSSortDescriptor alloc] initWithKey:@"position" ascending:YES];
我不确定如何访问和使用 PositionSort。有任何想法吗?谢谢!
更新:添加了完整的功能...
- (NSFetchedResultsController *)fetchedResultsController
{
if (__fetchedResultsController != nil) {
return __fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setFetchBatchSize:20];
NSSortDescriptor *sortDescriptorState = [[NSSortDescriptor alloc] initWithKey:@"position.positionSort" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptorState, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"(companyID == %@)", company.companyID];
[fetchRequest setPredicate:searchPredicate];
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"position.positionDescription" 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;
}
使用上面的代码,我在运行时
遇到了以下错误。
2012-08-12 10:29:45.499 College[269:707] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFString 0xd6bd310> valueForUndefinedKey:]: this class is not key value coding-compliant for the key positionDescription.'
最佳答案
我不确定你想要精确排序,但是下面的 NSSortDescriptor
可用于使用 PositionSort
对 Person
对象进行排序值(value)。
NSSortDescriptor *sortDescriptorPosition = [[NSSortDescriptor alloc] initWithKey:@"position.PositionSort" ascending:YES];
也许,你正在寻找这个......
关于objective-c - iOS:如何使用 NSSortDescriptor 对关系中的值进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11922006/