簡體   English   中英

按字典鍵排序可變數組

[英]Sorting mutable array by dictionary key

我已經使用NSMutableArray的各種排序方法查看了幾個答案,但由於某種原因它們不適合我。

我只是試圖通過每個字典中的Delay鍵對包含字典的可變數組進行排序。 但是,“sorted”數組與原始數組完全相同。

順便說一句,如果我創建一個虛擬可變數組並用包含數字的字典填充它,它可以正常工作,但由於某種原因它不會對我正在初始化的這個可變數組進行排序。

我究竟做錯了什么?

這是我的代碼:

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;
    }
)

當我在字典中使用NSNumber時,上面的代碼很好。 這讓我相信Delay值在字典中存儲為字符串。 您需要做的是按字符串integerValue排序。

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

請嘗試以下,它與我合作

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]];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM