情况:CoreData 数据库具有“联系人”实体和“Sum”属性(正数或负数或 0)
目标:具有 3 个部分的 tableviewcontroller,第一个正,第二个负,第三个(零)“已存档”
到目前为止:使用 @selector(compare:) 对描述符进行排序(没有谓词,因为需要所有联系人的列表)
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Contact"];
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"moneySum" ascending:YES selector:@selector(compare:)]];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.database.managedObjectContext
sectionNameKeyPath:@"sectionName"
cacheName:nil];
在联系人实体类别中:
- (NSString *)sectionName {
[self willAccessValueForKey:@"sectionName"];
NSString *sectionName;
double value = [[self valueForKey:@"moneySum"] doubleValue];
if (value > 0) sectionName = POS_SECTION;
else if (value < 0) sectionName = NEG_SECTION;
else sectionName = ARCHIVE_SECTION;
[self didAccessValueForKey:@"sectionName"];
return sectionName;
}
我现在确实得到了 3 个类别,但它显然将它们排序为存档在中间,而不是在最后。
我考虑过向 sortDescriptors 数组添加第二个 sortDescriptor (在比较之前:一个),但对我来说最直观的方法 (isEqualToNumber:) 显然不起作用,因为我无法指定任何参数 (@selector ( .. :) )还是我错了?
抱歉,对于整个编码来说还很陌生:)
最佳答案
摘自《核心数据编程指南》:
... To summarize, though, if you execute a fetch directly, you should typically not add Objective-C-based predicates or sort descriptors to the fetch request. Instead you should apply these to the results of the fetch.
这意味着您不能在获取请求中使用自定义排序描述符。您必须在实体中存储附加(非 transient )属性,例如“0”、“1”、“2”表示正/负/零和。
然后,您可以将此属性用于 sectionNameKeyPath
的排序描述符和,您不需要 transient 属性“sectionName”。
然后在 tableView:titleForHeaderInSection:
中完成从“0”、“1”、“2”到实际节标题的映射。
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.controller sections] objectAtIndex:section];
int order = [[sectionInfo name] intValue];
if (order == 0)
return @"POSITIVE SECTION";
else if (order == 1)
return @"NEGATIVE SECTION";
else
return @"ARCHIVE SECTION";
}
关于iphone - 按属性(数字)对实体进行排序,负数后等于 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12005685/