0

您好我有以下问题:

我正在编写游戏,每次玩家完成分数时都会提交。所以我有两个数据源:分数和模式。我想将这些高分分为 4 个部分,即我拥有的 4 种模式。在这些部分中,它应该按分数排序(最高的在顶部)。

然而我得到了这个代码:

- (NSFetchedResultsController *)fetchedResultsController{
if (_fetchedResultsController != nil) {
    return _fetchedResultsController;
}

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" 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:@"score" ascending:NO];
NSArray *sortDescriptors = @[sortDescriptor];

[fetchRequest setSortDescriptors:sortDescriptors];

// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;

_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"mode" cacheName:nil];
_fetchedResultsController.delegate = self;
[_fetchedResultsController performFetch:nil];

NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
     // Replace this implementation with code to handle the error appropriately.
     // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

return _fetchedResultsController;}

但我得到的只是一个非常随机的排序。第一次成功,但玩了几局后就搞砸了!我的模式是:10,20,30,60(秒) 左边的金色徽章显示它应该在哪个部分进行排序。希望有人能帮助我。

iPhone 截图

4

1 回答 1

0

您需要为模式和分数添加另一个排序描述符。

您需要先按模式排序,然后按分数排序。当您当前按分数排序并按名称分区时,您将获得...

Mode 1:
- Score 100
- Score 99
Mode 2:
- Score 80
Mode 1:
- Score 70
etc...

像这样更改您的排序描述符代码...

NSSortDescriptor *modeSD = [[NSSortDescriptor alloc] initWithKey:@"mode" ascending:YES];
NSSortDescriptor *scoreSD = [[NSSortDescriptor alloc] initWithKey:@"score" ascending:NO];
NSArray *sortDescriptors = @[modeSD, scoreSD];

[fetchRequest setSortDescriptors:sortDescriptors];

那应该为你排序(双关语非常有意;-))

如果您想要四个单独的部分,那么您的 NSFRC 将如下所示...

// note the section name key path
NSFetchedResultsController *nsfrc = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"mode" cacheName:nil];

然后,这会将数据拆分为部分和行。

节数是[[nsfrc allSections] count];

等等...

于 2013-02-03T22:25:53.273 回答