2012-06-04 260 views
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; 
    } 
) 

回答

8

工作上面的代碼是罰款當我在我的字典中使用NSNumber。這使我相信,Delay值存儲在你的字典字符串。你需要做的是按字符串排序integerValue

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

你說對了...這奏效了。我需要回去解決這個問題。謝謝! – ZeNewb

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

它起作用時,你初始化可變數組並添加類似的字典,但爲什麼不適用於我的情況下,當我已經有一個預填充可變數組?這就是我卡上:\ – ZeNewb

+0

您可以發佈用於填充你的字典代碼? –

+0

謝謝,但我是一個假人,並將它們存儲爲字符串。喬抓住了它,給了我一個修復。非常感謝! – ZeNewb