无法在ios中对Array进行排序

时间:2013-10-25 10:24:03

标签: ios objective-c sorting dictionary

我有一个NSMutableArray名称是xyz,array的每个元素都包含个人Dictionary。我想对这个主Dictionary进行排序,例如结构:

 $0 = 0x0963e730 <__NSArrayM 0x963e730>(
{
    accuracy = 0;
    context = 0;
    dateupload = 1382375073;
    description =     {
        "_content" = "";
    };
    farm = 4;
    id = 10406310594;
    isfamily = 0;
    isfriend = 0;
    ispublic = 1;
    latitude = 0;
    longitude = 0;
    owner = "35744@N03";
    ownername = abc;
    secret = f9fd3;
    server = 3830;
    tags = "";
    title = 17740013;
},
{
    accuracy = 0;
    context = 0;
    dateupload = 1382375072;
    description =     {
        "_content" = "";
    };
    farm = 8;
    id = 10406317735;
    isfamily = 0;
    isfriend = 0;
    ispublic = 1;
    latitude = 0;
    longitude = 0;
    owner = "35944@N03";
    ownername = abc;
    secret = 9665d3ec;
    server = 74;
    tags = "vision:food=0635";
    title = 01200033;
},

我想按标题排序这个数组;

我使用LinqToObjectiveC-master库但可以进行排序。

帮助这个解决方案,简单的解决方案高度赞赏。

2 个答案:

答案 0 :(得分:1)

试试这个: -

NSDictionary *person1 = [NSDictionary dictionaryWithObjectsAndKeys:@"d",@"name",@"xyz",@"add",nil];
NSDictionary *person2 = [NSDictionary dictionaryWithObjectsAndKeys:@"e",@"name",@"pqr",@"add",nil];
NSDictionary *person3 = [NSDictionary dictionaryWithObjectsAndKeys:@"a",@"name",@"stu",@"add",nil];

NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:person1,person2,person3,nil];

NSSortDescriptor *name = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
[arr sortUsingDescriptors:[NSArray arrayWithObject:name]];

// before sort
NSLog(@"Before %@",arr);
[arr sortedArrayUsingComparator:^(NSDictionary *item1, NSDictionary *item2) {
    NSString *first = [item1 objectForKey:@"name"];
    NSString *second = [item2 objectForKey:@"name"];
    return [first compare:second options:NSCaseInsensitiveSearch];
}];
// After sort
NSLog(@"After %@",arr);

答案 1 :(得分:0)

作为键/值集合,您无法对字典进行排序,但您可以按如下方式对值数组进行排序:

NSArray *dictionaryValues = [flickr allValues];

然后使用sortDescriptor

进行排序
NSSortDescriptor *nameSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSArray *flickrSortedValues = [dictionaryValues sortedArrayUsingDescriptors:@[descriptor]];