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

标签 ios objective-c nsfetchedresultscontroller nssortdescriptor nsset

我有一个名为 Delivery 的对象,它有一组与之关联的 Customer 对象。每个 Delivery 对象还存储一个 mainCustomerId,它是一个 NSNumber*。我有一个 NSFetchedResultsController,用于管理 UITableView 的数据源。问题是我想按客户的 lastName 字段对 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;

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

提前致谢。

最佳答案

好吧,也许我遗漏了一些东西,但谓词建议对我来说非常有意义。如果我错了请纠正我但是(假设你知道 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,然后按 lastName 对这些结果进行排序。这将在内部生成 SQL 语句来为您执行此操作。

这不是你想要做的吗?

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

-com.apple.CoreData.SQLDebug 1

快乐编码:)

关于ios - 使用属于实体的 NSSet 中的对象对 NSFetchedResultsController 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15167649/

相关文章:

iOS菜单标题到导航栏标题动画

ios - 根据用户位置动态绘制RMShape

ios - 为什么 Swift Int 零在 objc 代码中读取为 nil?

iphone - 如何在 iOS 中计算对数?

ios - NSFetchedResultsController -sectionNameForKeypath 如何获取其数据?

ios - Realm swift : passing unpersisted objects between threads

ios - 使用 segue 在 View Controller 之间传递变量

iphone - CGRectUnion() 的相反结果是什么?

ios - 设置 Controller 时 NSFetchedResultsController 崩溃

iphone - Matt Gallagher 的 UITableView(重访)+ NSFetchedResultsController