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

NSSortDescriptor for NSArrayController to sort alphabetically and by string length

我有一个 NSArrayController,我试图根据字符串的长度和字母顺序对它进行排序。 NSArrayController 包含一个带有 space 的字符串,例如 " ".

这是我的代码:

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

但这是排序的结果:

我首先需要的是字符串“”,然后是 aaa、bbb、cccc、ddd。

NSArrayController (nameAC)控制台输出:

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

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

(lldb) po _nameAC [实体:标签,选中对象数量: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;
})
)

你们中有人知道我做错了什么或者我该怎么做吗?

非常感谢你的帮助

内容数组包含标签实体的托管对象。这些对象确实有 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];