2013-12-08 124 views
1

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

我有点麻烦,因为我可以修复循环中的所有内容。

我所做的是,使用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]; 

感谢

回答

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

这就给了你一个字典,其中每个键是该部分的标题(日期字符串),每个值都是该部分的对象数组。

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

+0

感谢您的回复,但你能告诉我如何在数组中输入数据吗?我无法做到。非常感谢你 – Vins

相关问题