按日期对对象进行分组

时间:2013-12-08 22:54:22

标签: ios objective-c nsdate

我从服务器获取对象列表,并将日期作为属性。 我收到的自行车项目,我需要将它们安排在一张桌子上,但除以天数(按部分)。

我遇到了一些麻烦,因为我可以修复循环中的所有内容。

我所做的是,使用NSDateFormatteris创建一个包含部分数量的数组。但从逻辑上讲,我不知道如何在循环中创建所有内容。

NSMutableArray *singleSectionArray = [[NSMutableArray alloc] init];
NSMutableArray *sectionsArray = [[NSMutableArray alloc] init];

[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (!error) {
        int i = 0;
        NSDateFormatter *df = [[NSDateFormatter alloc] init];

        for (PFObject *object in objects) {
            [df setDateFormat:@"MMMM d EEEE"];
            NSString *dateString = [[NSString alloc] initWithFormat:@"%@",[df stringFromDate:object.createdAt]];
            NSArray *dateArray = [dateString componentsSeparatedByString:@" "];
            BOOL sectionExist = [sectionsArray containsObject:[dateArray objectAtIndex:1]];

            if (sectionExist == 0) {
                [sectionsArray addObject:[dateArray objectAtIndex:1]];
                [singleSectionArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                               object.createdAt,@"date",
                                               object.objectId,@"objectId",
                                               nil]];
            } else {
               //???
            }

        }

...

[self.tableView reloadData];

我会有这样的结构

//Section
NSArray *singleSectionArray = [[NSArray alloc] initWithObjects:@"Object 1", @"Object 2", @"Object 3", nil];
NSDictionary * singleSectionDictionary = [NSDictionary dictionaryWithObject: singleSectionArray forKey:@"data"];
[dataArray singleSectionDictionary];
//Section
NSArray *singleSectionArray = [[NSArray alloc] initWithObjects:@"Object 4", @"Object 5", nil];
NSDictionary * singleSectionDictionary = [NSDictionary dictionaryWithObject: singleSectionArray forKey:@"data"];
[dataArray singleSectionDictionary];

由于

1 个答案:

答案 0 :(得分:5)

这样的事情会起作用:

NSMutableDictionary *sections = [NSMutableDictionary dictionary];

for (PFObject *object in objects) {
    [df setDateFormat:@"MMMM d EEEE"];
    NSString *dateString = [df stringFromDate:object.createdAt];
    NSMutableArray *sectionArray = sections[dateString];
    if (!sectionArray) {
        sectionArray = [NSMutableArray array];
        sections[dateString] = sectionArray;
    }

    [sectionArray addObject:@{ @"date" : object.createdAt, @"objectId" : object.objectId }];
}

它为您提供了一个字典,其中每个键都是节标题(日期字符串),每个值都是该节的对象数组。

现在的诀窍是创建一个包含日期键的数组,以便按照您希望它们在表中显示的方式排序数组。您不能简单地对日期字符串进行排序,因为它们将按字母顺序排列而不是按时间顺序排列。

相关问题