我正在尝试在实体文件夹上执行获取请求,并且我希望名为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不会显示在最后,但所有内容最终都按字母顺序排序。我做错了吗?
修改:已发布完整代码
答案 0 :(得分: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委托设置中,代码中的其他位置。