【问题标题】:Sort NSFetchedResultsController with object in NSSet belonging to entity使用 NSSet 中属于实体的对象对 NSFetchedResultsController 进行排序
【发布时间】:2013-03-01 22:05:49
【问题描述】:

我有一个名为Delivery 的对象,它有一组与之关联的Customer 对象。每个 Delivery 对象还存储一个mainCustomerId,它是一个NSNumber*。我有一个 NSFetchedResultsController 用于管理 UITableView 的数据源。问题是我想按客户的姓氏字段对 NSFetchedResultsController 进行排序(客户再次存储在Delivery 对象上称为customers 的多对多关系中)其中一个客户有一个customerId 等于 Delivery 的 MainCustomerId。

交付类看起来像这样(仅相关部分)

@interface Delivery : NSManagedObject
@property (nonatomic, retain) NSNumber * mainCustomerId;
@property (nonatomic, retain) NSSet *customers;
@end

客户类如下所示

@interface Customer : NSManagedObject
@property (nonatomic, retain) NSNumber * customerId;
@property (nonatomic, retain) NSString * lastName;
// And the inverse relationship to the deliveries
@property (nonatomic, retain) NSSet *deliveries;
@end

我需要制作一个 NSSortDescriptor 来做这样的事情(注意,我知道这是错误的格式并且不会起作用。我希望它可以传达这个想法)

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"customers.AnyobjectInSet.lastName WHERE AnyobjectInSet.customerId == masterCustomerId ascending:YES];

我使用子查询和 NSExpressions 尝试了几件事,但总是失败,因为我不能使用任何使用 Cocoa 的功能(比如使用 @selector 排序),因为它必须能够生成一个没有 Cocoa 的真实 mysql 查询数据的处理。但我觉得必须有办法做到这一点,因为这在 mysql 中是一个简单的查询。

select * from Delivery JOIN Customer ON Customer.customerId=Delivery.mainCustomerId ORDER BY Customer.lastName;

我试图避免在获取结果后进行排序并将排序顺序存储回对象(这很容易,但我觉得这是错误的解决方案,因为我选择了相关数据。必须是一种按它排序的方法)。任何帮助将不胜感激。

提前致谢。

【问题讨论】:

  • 为什么不使用谓词然后应用排序描述符。
  • 谢谢Leena,我不太确定如何使用谓词来解决这个问题。我没有用任何东西过滤我的结果。我只需要通过具有相应 ID 的客户对象来订购它们。你有一个例子来说明你的意思吗?
  • 这有关系吗?它可以让你使用这种多对多的模型。 stackoverflow.com/questions/2328585/…
  • 为什么不将 mainCustomerId 替换为(一对一)关系 mainCustomer(从 Delivery 到 Customer)?这将更符合 Core Data 的精神(我认为)并使排序描述符变得微不足道。

标签: ios objective-c nsfetchedresultscontroller nssortdescriptor nsset


【解决方案1】:

好吧,也许我遗漏了一些东西,但谓词建议对我来说非常有意义。如果我错了,请纠正我(假设你知道 mainCustomerID):

NSNumber *mainCustomerID = ...

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"customerID == %@", mainCustomerID];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES];

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Customer"];
[request setPredicate:predicate];
[request setSortDescriptors:@[ sortDescriptor ]];

NSFetchedResultsController *controller = [[NSFetchedResultsController alloc] initWithFetchRequest:request ...

所以基本上如果不清楚,这将获取 customerID 等于 mainCustomerID 的所有客户记录,然后按姓氏对这些结果进行排序。这将在内部生成 SQL 语句来为您执行此操作。

这不是你想要做的吗?

此外,如果您想查看 CoreData 在运行时生成的 SQL(有用的调试工具),请打开您的方案并转到“参数”选项卡并将以下内容添加到“启动时传递的参数”中:

-com.apple.CoreData.SQLDebug 1

快乐编码:)

【讨论】:

  • 感谢 Shapps,但我所做的并不完全是。我在我的单元格中显示交付对象,并希望按与引用的主客户具有相同 ID 的 NSSet 中的客户进行排序。客户集合属于交付实体的位置。基本上,我需要对属于获取实体的 NSSet 中的特定对象进行排序。祝您编码愉快。
猜你喜欢
  • 2011-05-26
  • 2011-01-26
  • 1970-01-01
  • 2013-07-21
  • 1970-01-01
  • 2012-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多