【问题标题】:Sorting mutable array by dictionary key按字典键对可变数组进行排序
【发布时间】:2012-06-05 04:17:58
【问题描述】:

我已经使用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;
    }
)

【问题讨论】:

    标签: iphone objective-c ios sorting nsmutablearray


    【解决方案1】:

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

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

    【讨论】:

    • 是的,你是...成功了。我需要回去解决这个问题。谢谢!
    【解决方案2】:

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

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

    【讨论】:

    • 当你初始化可变数组并添加这样的字典时它可以工作,但是当我已经有一个预先填充的可变数组时,为什么它不适用于我的情况?这就是我坚持的:\
    • 谢谢,但我是个傻瓜,将它们存储为字符串。乔抓住了它并给了我一个修复。还是谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-04-17
    • 2019-11-18
    • 2016-03-03
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多