使用属于实体的NSSet中的对象对NSFetchedResultsController进行排序

joh*_*chd 5 objective-c nssortdescriptor nsset nsfetchedresultscontroller ios

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

交货类看起来像这样(只有相关部分)

@interface Delivery : NSManagedObject
@property (nonatomic, retain) NSNumber * mainCustomerId;
@property (nonatomic, retain) NSSet *customers;
@end
Run Code Online (Sandbox Code Playgroud)

客户类看起来像这样

@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
Run Code Online (Sandbox Code Playgroud)

我需要创建一个类似这样的NSSortDescriptor(注意,我知道这是错误的格式并且不起作用.我希望它能传达这个想法)

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"customers.AnyobjectInSet.lastName WHERE AnyobjectInSet.customerId == masterCustomerId ascending:YES];
Run Code Online (Sandbox Code Playgroud)

我已经尝试了几个使用子查询和NSExpressions的东西,但总是很短,因为我不能使用任何使用Cocoa的功能(比如使用@selector进行排序),因为它必须能够生成一个真正的mysql查询而没有C​​ocoa处理数据.但我觉得必须要做到这一点,因为它在mysql中是一个简单的查询.

select * from Delivery JOIN Customer ON Customer.customerId=Delivery.mainCustomerId ORDER BY Customer.lastName;
Run Code Online (Sandbox Code Playgroud)

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

提前致谢.

Sha*_*aps 2

好吧,也许我错过了一些东西,但谓词建议对我来说非常有意义。如果我错了,请纠正我,但是(假设您知道 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 ...
Run Code Online (Sandbox Code Playgroud)

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

这不是你想做的吗?

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

-com.apple.CoreData.SQLDebug 1
Run Code Online (Sandbox Code Playgroud)

快乐编码:)