Sort NSDates inside NSDictionary inside NSArray?

梦想的初衷 提交于 2019-12-13 01:14:33

问题


Currently in my app I have a NSArray that I load from NSUserDefaults. Each object in the NSArray is a NSDictionary that has about 5 different keys. I am re-order the NSDictionarys themselves based upon the NSDates inside of them. I do not want to sort the NSDates alone.

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.

Can anyone offer any insight on this?

Thanks!


回答1:


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.

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

    }];


来源:https://stackoverflow.com/questions/10668392/sort-nsdates-inside-nsdictionary-inside-nsarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!