gpt4 book ai didi

ios - Core Data 中多对多关系的 sectionNameKeyPath 值

转载 作者:行者123 更新时间:2023-11-29 11:03:44 26 4
gpt4 key购买 nike

我有一个包含三个实体的核心数据模型:NotificationGroupCustomer。它们之间的关系如下:

  • 一个客户属于多个组,一个组可以有多个客户。
  • 一个通知被发送(属于)一个组,一个组可以接收(拥有)许多通知。

我想在按客户分组的 UITableView 中显示所有通知。我创建了一个像这样的 NSFetchedResultsController:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
fetchRequest.fetchBatchSize = 10;
fetchRequest.predicate = nil;

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Notification"
inManagedObjectContext:self.managedObjectContext];
fetchRequest.entity = entity;

// Default sort descriptors are built in a separate custom method
NSArray *sortDescriptors = [self getDefaultSortDescriptorsForEntity:entity];
fetchRequest.sortDescriptors = sortDescriptors;

return [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:@"group.customers.firstName"
cacheName:nil];

假设这是检索按客户分组的所有通知的有效方法(我也不确定)iOS 抛出以下异常:

@"Failed to fetch all Notification objects"
@"Reason: Invalid to many relationship in setPropertiesToFetch: (group.customers.firstName) (NSInvalidArgumentException)"

我一遍又一遍地检查关系,看看是否缺少某些东西并且一切似乎都是正确的。我可以为所有实体创建和删除对象,它们之间的链接也是正确的。

我的问题是:是否可以遍历 sectionNameKeyPath 值中的多个关系?这种场景应该如何处理多对多关系?

最佳答案

是的,你可以做到这一点。只需使用 FRC 获取客户并将 sectionNameKeyPath 设置为 nil

章节
返回的结果数就是您的部分数。使用客户数据填充节标题。


部分中的行数将为 customer.notifications.count。要填充该行,请确保以某种方式(例如,按日期)对 notifications 进行了排序,并使用如下内容相应地显示它们:

NSArray *orderedNotifications = 
[customerForSection.notifications sortedArrayUsingDescriptors:
@[[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO]]];
Notification *notificationToBeDisplayed =
[orderedNotifications objectAtIndex:indexPath.row];

另一种推荐的解决方案是更改数据模型。您可以将通知直接与所有客户相关联。这会带来额外的优势,即使群组成员身份发生变化,通知仍会与正确的客户相关联。

关于ios - Core Data 中多对多关系的 sectionNameKeyPath 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14627106/

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