NSArrayController的NSSortDescriptor按字母顺序和字符串长度排序

时间:2015-03-22 22:58:09

标签: cocoa nstableview nsarraycontroller nssortdescriptor

我有一个NSArrayController,我试图根据字符串的长度和字母顺序对它进行排序。 NSArrayController包含一个字符串,其空间类似于“”。

这是我的代码:

    NSSortDescriptor *nameSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    NSSortDescriptor *lengthSorter = [NSSortDescriptor sortDescriptorWithKey:@"length" ascending:YES];
[self.nameAC.content setSortDescriptors:@[lengthSorter, nameSortDescriptor]];

但这是排序的结果:

enter image description here 我需要首先在字符串“”和aaa,bbb,cccc,ddd之后。

NSArrayController(nameAC)控制台中的输出:

(lldb) po _nameAC
<NSArrayController: 0x6080001c05a0>[entity: Tags, number of selected objects: 1]

NSArrayController内容的控制台中的输出如下:

(lldb)po _nameAC [entity:Tags,所选对象的数量:1]

(lldb) po _nameAC.content
<__NSArrayM 0x60000004f600>(
<Tags: 0x6000000a7260> (entity: Tags; id: 0x140002b <x-coredata://B7756C1E-B9F2-4C57-A1FA-272478C4D6A6/Tags/p5> ; data: {
    category = "0x40000b <x-coredata://B7756C1E-B9F2-4C57-A1FA-272478C4D6A6/Categories/p1>";
    product = "<relationship fault: 0x60800002ba80 'product'>";
    name = bbb;
}),
<Tags: 0x6000000a7200> (entity: Tags; id: 0x100002b <x-coredata://B7756C1E-B9F2-4C57-A1FA-272478C4D6A6/Tags/p4> ; data: {
    category = "0x40000b <x-coredata://B7756C1E-B9F2-4C57-A1FA-272478C4D6A6/Categories/p1>";
    product = "<relationship fault: 0x60800002a160 'product'>";
    name = aaa;
}),
<Tags: 0x6000000a7740> (entity: Tags; id: 0x1c0002b <x-coredata://B7756C1E-B9F2-4C57-A1FA-272478C4D6A6/Tags/p7> ; data: {
    category = "0x40000b <x-coredata://B7756C1E-B9F2-4C57-A1FA-272478C4D6A6/Categories/p1>";
    product = "<relationship fault: 0x60800002b940 'product'>";
    tagName = ddd;
}),
<Tags: 0x6000000a5ca0> (entity: Tags; id: 0x40002b <x-coredata://B7756C1E-B9F2-4C57-A1FA-272478C4D6A6/Tags/p1> ; data: {
    category = "0x40000b <x-coredata://B7756C1E-B9F2-4C57-A1FA-272478C4D6A6/Categories/p1>";
    product = "<relationship fault: 0x6080000283e0 'product'>";
    name = " ";
}),
<Tags: 0x6000000a76e0> (entity: Tags; id: 0x180002b <x-coredata://B7756C1E-B9F2-4C57-A1FA-272478C4D6A6/Tags/p6> ; data: {
    category = "0x40000b <x-coredata://B7756C1E-B9F2-4C57-A1FA-272478C4D6A6/Categories/p1>";
    product = "<relationship fault: 0x60800002a620 'product'>";
    name = cccc;
})
)

你们中的任何人都知道我做错了什么或者我该怎么做?

我真的很感谢你的帮助

1 个答案:

答案 0 :(得分:2)

内容数组包含Tags实体的托管对象。这些对象确实具有name属性,但它们没有length属性。

如果要构建按name的长度排序的排序描述符,则应使用密钥路径name.length。所以:

NSSortDescriptor *lengthSorter = [NSSortDescriptor sortDescriptorWithKey:@"name.length" ascending:YES];

此外,应在阵列控制器上设置排序描述符。所以,你在哪里写道:

[self.nameAC.content setSortDescriptors:@[lengthSorter, nameSortDescriptor]];

它应该是:

[self.nameAC setSortDescriptors:@[lengthSorter, nameSortDescriptor]];

或只是:

self.nameAC.sortDescriptors = @[lengthSorter, nameSortDescriptor];