【问题标题】:Sort the Main NSArray using the SubArray key value pair使用 SubArray 键值对对 Main NSArray 进行排序
【发布时间】:2014-10-10 07:27:04
【问题描述】:

我想根据数组 self.contacts 中的 first_name 对我的主数组进行排序

用于对数组进行排序的代码

-(void)Sort
{
     NSSortDescriptor *sdName = [[NSSortDescriptor alloc] initWithKey:@"first_name" ascending:YES];
     self.contacts = [NSMutableArray arrayWithArray:[self.contacts sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sdName, nil]]];
}

我的数据

self.contacts = (
        {
            contact = {
                "first_name" = "Test R";
            };

            "last_met" = (
                {
                    "last_met_date" = "2014-10-09";
                }
            );
        },
        {
            contact = {
                "first_name" = "Test K";
            };

            "last_met" = (
                {
                    "last_met_date" = "2014-10-09";

                }
            );
        }
    )

【问题讨论】:

  • 请添加更多信息。你的问题很模糊。

标签: objective-c xcode nsarray nssortdescriptor


【解决方案1】:

试试这个排序描述符:

descriptor = [[NSSortDescriptor alloc] initWithKey:@"contact.first_name" 
                                         ascending:YES];

参数key实际上是一个key pathNSDictionary是KV兼容的。你可以写这样的东西:[contacts[0] valueForKeyPath:@"contact.first_name"]

【讨论】:

    【解决方案2】:

    查看您的代码,您似乎想要对联系人数组进行排序,这是一个字典数组,我在这里提供的解决方案就是针对这种情况的。

    你可以这样做:

    NSArray *sortedContactsArray = [self.contacts sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSString *first_name1 = [obj1 valueForKeyPath:@"contact.first_name"];
        NSString *first_name2 = [obj2 valueForKeyPath:@"contact.first_name"];
    
        return [first_name1 compare:first_name2];
    }];
    

    请注意,它可能并不安全和最佳,但这只是其中一种方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多