gpt4 book ai didi

objective-c - NSFetchedResultController。使用表达式/按条件计算 sectionNameKeyPath

转载 作者:行者123 更新时间:2023-11-29 13:32:50 24 4
gpt4 key购买 nike

假设有一个名为 testTable 的表:

(NSNumber*) numValue
(NSString*) stringValue

那么假设里面大概有50条记录。 numValue 每条记录都不一样。如果我像这样创建 NSFetchedResultController:

NSFetchRequest *request = [[NSFetchedResultsController alloc] 
initWithFetchRequest: request
managedObjectContext: context
sectionNameKeyPath: @"numValue"
cacheName: @"testTable"]];

那我会得到 50 个部分。

我的问题是:我怎样才能得到2个部分:第一个包含 numValue 小于某个 x 的记录,第二个包含 numValue 大于相同 x 的记录。

对于 x = 15,它可能看起来像这样:

NSFetchRequest *request = [[NSFetchedResultsController alloc] 
initWithFetchRequest: request
managedObjectContext: context
sectionNameKeyPath: @"numValue > 15"
cacheName: @"testTable"]];

可能的解决方案是:

  1. 我们可以像@Dima 所说的那样编辑我们的实体。
  2. numberOfSectionsInTableView: 中,我们可以只查看部分名称并将它们与 x 进行比较。然后我们可以在 tableView:numberOfRowsInSection: 中查看这些名称并计算我们需要的内容。但这也感觉很脏。比第一种方法更好,但仍然如此。

更新:好吧,我几乎想出了第三种方法来做到这一点。感谢@Dima 的链接。这是代码:

[self setFetchedResultsController: [[NSFetchedResultsController alloc]
initWithFetchRequest: request
managedObjectContext: context
sectionNameKeyPath: [NSString stringWithFormat: @"numValue.compare(%f)", x]];

但 KVC 合规性存在问题:带有参数的方法(选择器)显然不符合 KVC。有解决方法吗?

最佳答案

参见 this回答作为引用。

向实体添加可选属性并使其成为 transient 属性。

然后创建一个getter(假设你的属性叫做sectionGroup)

- (NSNumber *) sectionGroup
{
[self willAccessValueForKey:@"sectionGroup"];
NSNumber *group = [NSNumber numberWithInt:0];
if(numValue > 15)
{
group = [NSNumber numberWithInt:1];
}
[self didAccessValueForKey:@"sectionGroup"];
return group;
}

现在,您可以使用 sectionGroup 作为您的 sectionNameKeyPath。

关于objective-c - NSFetchedResultController。使用表达式/按条件计算 sectionNameKeyPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11433759/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com