-1

我需要用“姓氏”对给定的“文档”数组进行排序。这是示例 json

document [
{
    id:"100"
    person :{
       name : {
        firstname : "xyz",
        lastname  : "oops"
       },
       photourl: "photo-url"
    }
},
{
    id:"200"
    person :{
       name : {
        firstname : "xyz",
        lastname  : "oops"
       },
       photourl: "photo-url"
    }
}]

它在另一个字典“人”中有一个字典“名称”,我们需要先用姓氏排序,然后用姓氏排序

4

5 回答 5

1
NSSortDescriptor *lastNameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastname " ascending:YES] ;
NSArray *sortedArray = [NSArray arrayWithObject:lastNameDescriptor];
sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];

为了更清晰的描述和代码检查这个链接,它非常简单和完美,干杯:)

于 2013-07-10T12:37:45.760 回答
0

因此,假设您将 JSON 放入一个名为“people”的数组中:

NSArray *people = myArrayFromJSON;

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"person" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {
    NSString *lastName1 = [obj1 valueForKey:@"lastname"];
    NSString *lastname2 = [obj2 valueForKey:@"lastname"];

    return [lastName1 compare:lastname2];
}];

NSArray *sortedArray = [people sortedArrayUsingDescriptors:@[sortDescriptor]];

这样就可以了。

于 2013-07-10T14:10:43.777 回答
0

使用下面给定的逻辑

for (NSMutableDictionary *document in documents) {
    NSString *lastName = [[document valueForKey:@"person"] valueForKey:@"lastname"];
    [documents setObject:lastName forKey:@"lastnameDescriptor"];
}

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"lastnameDescriptor" ascending:YES];
NSMutableArray *sortedNames = [documents sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];

for (NSMutableDictionary *document in sortedNames) {
    [document removeObjectForKey:@"lastnameDescriptor"];
}
于 2013-07-10T15:44:27.727 回答
0

其他答案很接近,但要么不必要地复杂,要么有点偏离。

NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"person.lastName" ascending:YES];
sortedArray = [document sortedArrayUSingDescriptors:@[descriptor]];

(选择器说“key”,但如果你阅读文档,它实际上是一个 keypath,所以这将按预期工作。)

于 2013-07-11T05:15:08.443 回答
0

许多几乎正确的答案,但没有一个认为“名称”本身就是文档中的嵌套字典。所以我认为你想要的是:

NSSortDescriptor *lastNameDescriptor = [NSSortDescriptor sortDescriptorWithkey:@"person.name.lastname" ascending:YES];
NSSortDescriptor *firstNameDescriptor = [NSSorteDescriptor sortDescriptorWithKey:@"person.name.firstname" ascending:YES];
NSArray *sortedArray = [document sortedArrayUsingDescriptors:@[lastNameDescriptor, firstNameDescriptor]];
于 2013-07-11T05:40:58.940 回答