简体   繁体   English

在NSArray中的NSDictionary中对NSDates进行排序?

[英]Sort NSDates inside NSDictionary inside NSArray?

Currently in my app I have a NSArray that I load from NSUserDefaults. 当前在我的应用程序中,我有一个从NSUserDefaults加载的NSArray。 Each object in the NSArray is a NSDictionary that has about 5 different keys. NSArray中的每个对象都是一个NSDictionary,具有大约5个不同的键。 I am re-order the NSDictionarys themselves based upon the NSDates inside of them. 我根据其中的NSDate重新排序NSDictionary I do not want to sort the NSDates alone. 我不想单独对NSDates进行排序。

I have tried to do this with this code: 我尝试使用以下代码执行此操作:

NSComparator sortByDate = ^(id dict1, id dict2) {
        NSDate* n1 = [dict1 objectForKey:@"Date"];
        NSDate* n2 = [dict2 objectForKey:@"Date"];
        return (NSComparisonResult)[n1 compare:n2];
    };
    [self.cellArray sortUsingComparator:sortByDate];

Although nothing happens even though the code gets executed. 尽管即使执行了代码也没有任何反应。 I am confused though about how to re-order the NSDictionarys based upon something inside of it. 我对如何根据NSDictionary中的内容重新排序感到困惑。

Can anyone offer any insight on this? 谁能对此提供任何见解?

Thanks! 谢谢!

You could try sorting it inline but I doubt that would have any major effect. 您可以尝试以内联方式对其进行排序,但是我怀疑这会产生重大影响。 But I can say i never abstract out my blocks. 但是我可以说我永远不会抽象出我的障碍。 I would definitely try NSLogging too to make sure you're getting valid NSDates. 我也肯定会尝试使用NSLogging来确保您获得有效的NSDate。

    [cells sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSDate *n1 = [obj1 objectForKey:@"Date"];
        NSDate *n2 = [obj2 objectForKey:@"Date"];

        if (n1 > n2) {
            return NSOrderedAscending;
        } else (n1 < n2) {
            return NSOrderedDescending;
        } else {
            return NSOrderedSame;
        }

    }];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM