2011-09-08 82 views
1

我有一個陣列NSMutableArray與值說 10,2,13,4排序的NSMutableDictionary基於在NSMutable陣列內容

也有是NSMutableDictionary與值說 (10,A),(20,B ),(13,c),(2,d),(33,e)

我想排序NSMutableDictionary中的值,使字典結果爲(10,a),(2,d) ,(13,c)

+0

你想刪除不在陣的值字典? – Nekto

+0

是的。你是對的。 – MacGeek

+0

查看我的答案,希望能幫到你。 – Nekto

回答

1

我爲你寫的函數。希望它能幫助你:

- (void)removeUnnedful 
{ 
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys: 
          @"a", [NSNumber numberWithInt:10], 
          @"b", [NSNumber numberWithInt:20], 
          @"c", [NSNumber numberWithInt:13], 
          @"d", [NSNumber numberWithInt:2 ], 
          @"e", [NSNumber numberWithInt:33], 
          nil]; 
    NSMutableArray *array = [[NSMutableArray alloc] initWithObjects: 
          [NSNumber numberWithInt:10], 
          [NSNumber numberWithInt:2 ], 
          [NSNumber numberWithInt:13], 
          [NSNumber numberWithInt:14], nil]; 

    NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init]; 
    for (NSNumber *key in [dict allKeys]) 
    { 
     NSLog(@"%@", key); 
     if ([array containsObject:key]) 
     { 
      [newDict setObject:[dict objectForKey:key] forKey:key]; 
     } 
    } 

    for (NSNumber *key in [newDict allKeys]) 
     NSLog(@"key: %@, value: %@", key, [newDict objectForKey:key]); 

    [dict release]; 
    [array release]; 
} 
1

沒有定義在NSDictionary實例中鍵和值的排序順序。 (見[NSDictionary allKeys]
正如你已經有訂購的按鍵陣列,你可以簡單地在該迭代,該鍵訪問字典值:

NSMutableArray* sortedArray = [NSMutableArray arrayWithObjects:@"10", @"2", @"13", @"4", nil]; 
NSDictionary* dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"a", @"10", @"b", @"20", @"c", @"13", @"d", @"2", @"e", @"33" , nil]; 
NSMutableDictionary* filteredDictionary = [NSMutableDictionary dictionary]; 
for(id key in sortedArray) 
{ 
    id value = [dictionary objectForKey:key]; 
    if(value != nil) 
    { 
     [filteredDictionary setObject:[dictionary objectForKey:key] forKey:key]; 
    } 
} 
NSLog(@"%@", filteredDictionary); 

注意的[NSDictionary description]種種每輸出上升的默認實現鍵(NSString型的鍵),但這只是一種表象 - NSDictionaries沒有定義的排序順序,所以你不應該依靠allKeys排序和allValues

+0

你剛剛重複我的答案.... – Nekto