1

我正在尝试对实体文件夹执行提取请求,并且我希望一个文件夹命名xyz为排序时的最后一个对象。

  NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription 
                                   entityForName:@"Folder" inManagedObjectContext:appDelegate.managedObjectContext];

    [fetchRequest setEntity:entity];

    NSSortDescriptor *lastDescriptor =
    [[[NSSortDescriptor alloc] initWithKey:@"folderName" ascending:YES comparator:^NSComparisonResult(NSString* name1, NSString* name2) {
        NSLog(@"descriptor");
        if ([name1 isEqualToString:@"xyz"]) {
            return NSOrderedAscending;
        }
        if ([name2 isEqualToString:@"xyz"]) {
            return NSOrderedDescending;
        }

        return [name1 compare:name2];
    }] autorelease];  


    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:lastDescriptor]];
    [fetchRequest setFetchBatchSize:5];

    NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:appDelegate.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
    self.fetchedResultsController = theFetchedResultsController;
    self.fetchedResultsController.delegate=self;   

    [fetchRequest release];
    [theFetchedResultsController release];

    NSError *error;
    if (![[self fetchedResultsController] performFetch:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        exit(-1);  // Fail
    }

但是没有调用任何 NSLog 语句。他们应该这样做吗?并且文件夹 xyz 没有出现在最后,但所有内容最终都按字母顺序排序。难道我做错了什么?

Edit: Posted full code

4

1 回答 1

1

此代码(您的代码)有效:

- (void)sortMe {

    NSDictionary *d0 = [NSDictionary dictionaryWithObject:@"efg" forKey:@"folderName"];
    NSDictionary *d1 = [NSDictionary dictionaryWithObject:@"xyz" forKey:@"folderName"];
    NSDictionary *d2 = [NSDictionary dictionaryWithObject:@"abc" forKey:@"folderName"];
    NSDictionary *d3 = [NSDictionary dictionaryWithObject:@"def" forKey:@"folderName"];
    NSArray *testMe = [NSArray arrayWithObjects:d0, d1, d2, d3, nil];

    NSSortDescriptor *lastDescriptor =
    [[NSSortDescriptor alloc] initWithKey:@"folderName" ascending:YES comparator:^NSComparisonResult(NSString* name1, NSString* name2) {
        NSLog(@"descriptor");
        if ([name1 isEqualToString:@"xyz"]) {
            return NSOrderedAscending;
        }
        if ([name2 isEqualToString:@"xyz"]) {
            return NSOrderedDescending;
        }

        return [name1 compare:name2];
    }];

    NSArray *sorted = [testMe sortedArrayUsingDescriptors:[NSArray arrayWithObject:lastDescriptor]];
    for (NSDictionary *d in sorted) {
        NSLog(@"value=%@", [d valueForKey:@"folderName"]);
    }
}

我预测这段代码也会起作用:

NSError *error;
NSArray *result =  [appDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];
// log the array

我认为问题出在代码中其他地方的 NSFetchedResultsController 委托设置中。

于 2012-04-11T16:11:28.267 回答