我有两个具有一对多关系的CoreData实体 - Contact
(主要)和PhoneNumber
(相关)
联系人可以有多个电话号码,我需要按Contacts
属性对PhoneNumbers
进行排序,我想根据true
属性中现有的registered
值对其进行排序,例如:
Contact1 prop1 = "value1" prop2 = "value2" PhoneNumbers = [ {prop1 = "value1", prop2 = "value2", registered = false}, {prop1 = "value1", prop2 = "value2", registered = false} ] Contact2 prop1 = "value1" prop2 = "value2" PhoneNumbers = [ {prop1 = "value1", prop2 = "value2", registered = false}, {prop1 = "value1", prop2 = "value2", registered = false}, {prop1 = "value1", prop2 = "value2", registered = true} ] Contact3 prop1 = "value1" prop2 = "value2" PhoneNumbers = [ {prop1 = "value1", prop2 = "value2", registered = false}, {prop1 = "value1", prop2 = "value2", registered = false} ]
Contact2
PhoneNumber
registered = true
[NSSortDescriptor sortDescriptorWithKey:@"phoneNumbers" ascending:YES selector:@selector(registeredCompare:)];
,我希望将其移至获取结果的顶部
我的排序描述符:
phoneNumbers
当我指定Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'to-many key not allowed here'
键(作为数据模型中的关系)时,我收到错误unsupported NSSortDescriptor selector: registeredCompare:
当我将密钥更改为另一个密钥时,即使参数类型正确,错误也会更改为NSSortDescriptor sortDescriptorWithKey:ascending:comparator:
如何按相关属性对数据进行排序?
{p}NSFetchRequest
不支持比较器(bee new my_project
)
获取所有值到数组并排序它不是一个解决方案 - 太多的联系人可以冻结应用程序
答案 0 :(得分:0)
您无法按多对多关系进行排序。每个联系人可能有几个PhoneNumbers;要确定哪个联系人首先出现,CoreData需要为每个联系人提供一个值。
您的第二个错误是因为registeredCompare
不是可识别的排序选择器。来自Core Data Programming Guide:
SQLite支持的排序选择器是compare:和caseInsensitiveCompare:,localizedCompare:,localizedCaseInsensitiveCompare:和localizedStandardCompare:。
您的问题的一个解决方案是向Contact
实体添加布尔属性,比如hasRegisteredPhoneNumber
,当您添加/更改/删除相关的PhoneNumbers时,您将更新为true或false。然后使用该新属性作为排序键。