iOS:如何使用NSSortDescriptor对关系中的值进行排序?

时间:2012-08-12 12:04:12

标签: objective-c ios ios5 sorting nssortdescriptor

我的数据模型中有两个关系对象...

  1. 人{姓名,职位,职称}
  2. 职位{position,PositionSort}
  3. 以上每个都有自己的类文件(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;
    }
    

    使用上面的代码我在Runtime收到了以下错误。

    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.'
    

1 个答案:

答案 0 :(得分:6)

我不确定您要完全排序,但可以使用以下NSSortDescriptor来使用Person值对PositionSort个对象进行排序。

NSSortDescriptor *sortDescriptorPosition = [[NSSortDescriptor alloc] initWithKey:@"position.PositionSort" ascending:YES];
或许,你找了这个......