排序由字典键可变数组(Sorting mutable array by dictionary key

2019-09-17 17:48发布

我已经使用过的各种排序方法的几个答案看上去NSMutableArray ,但出于某种原因,他们不是为我工作。

我只是想其中由包含字典的可变数组排序Delay每个字典内的关键。 然而,“分类”阵列是完全相同的原阵列。

顺便说一句,如果我创建一个虚拟可变数组,并包含数字字典填充它,但由于某种原因它不会排序,我这个初始化可变数组它工作正常。

我究竟做错了什么?

这里是我的代码:

playlistCalls = [[NSMutableArray alloc] initWithArray:[currentPlaylist objectForKey:@"Tunes"]];

NSLog(@"original %@", playlistCalls);

NSSortDescriptor *delay = [NSSortDescriptor sortDescriptorWithKey:@"Delay" ascending:YES];
[playlistCalls sortUsingDescriptors:[NSArray arrayWithObject:delay]];

NSLog(@"sorted %@", playlistCalls);

下面是一个包含字典的数组:

2012-06-04 15:48:09.129 MyApp[57043:f503] original (
        {
        Name = Test Tune;
        Delay = 120;
        Volume = 100;
    },
        {
        Name = Testes;
        Delay = 180;
        Volume = 100;
    },
        {
        Name = Testing;
        Delay = 60;
        Volume = 100;
    }
)

2012-06-04 15:48:09.129 MyApp[57043:f503] sorted (
        {
        Name = Test Tune;
        Delay = 120;
        Volume = 100;
    },
        {
        Name = Testes;
        Delay = 180;
        Volume = 100;
    },
        {
        Name = Testing;
        Delay = 60;
        Volume = 100;
    }
)

Answer 1:

上面的代码是好的,当我使用NSNumber在我的字典秒。 这使我相信, Delay值存储在你的字典字符串。 你将需要做的,然后由字符串排序是integerValue

NSSortDescriptor *delay = 
   [NSSortDescriptor sortDescriptorWithKey:@"Delay.integerValue" ascending:YES];


Answer 2:

Please try the following, it worked with me

NSDictionary *dic;
NSMutableArray *arr = [[NSMutableArray alloc] init];

dic = [NSDictionary dictionaryWithObjectsAndKeys:
        [NSNumber numberWithInt:120], @"Delay",
        [NSNumber numberWithInt:100], @"Volume",
       nil];
[arr addObject:dic];

dic = [NSDictionary dictionaryWithObjectsAndKeys:
       [NSNumber numberWithInt:160], @"Delay",
       [NSNumber numberWithInt:100], @"Volume",
       nil];
[arr addObject:dic];

dic = [NSDictionary dictionaryWithObjectsAndKeys:
       [NSNumber numberWithInt:100], @"Delay",
       [NSNumber numberWithInt:100], @"Volume",
       nil];
[arr addObject:dic];

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


文章来源: Sorting mutable array by dictionary key