6

我已经使用 的各种排序方法查看了一些答案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;
    }
)
4

2 回答 2

8

当我NSNumber在字典中使用 s 时,上面的代码很好。这使我相信该Delay值作为字符串存储在您的字典中。然后您需要做的是按字符串排序integerValue

NSSortDescriptor *delay = 
   [NSSortDescriptor sortDescriptorWithKey:@"Delay.integerValue" ascending:YES];
于 2012-06-04T20:09:54.430 回答
1

请尝试以下方法,它对我有用

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]];
于 2012-06-04T20:06:54.510 回答