如何将NSMutableArray分组并在UITableView中显示?

时间:2013-06-06 09:33:17

标签: uitableview nsmutablearray grouping

我从服务器获取json并将它们添加到NSMutableArray中,如下所示:

{
  "title": "title60",
  "summary": "summary60",
  "datetime": "2013.02.03",
}
{
  "id": 58,
  "title": "title59",
  "summary": "summary59",
  "datetime": "2013.02.03",
},
{
  "id": 57,
  "title": "title58",
  "summary": "summary58",
  "datetime": "2013.02.04",
},
{
  "id": 56,
  "title": "title57",
  "summary": "summary57",
  "datetime": "2013.02.04",
},
{
  "id": 55,
  "title": "title56",
  "summary": "summary56",
  "datetime": "2013.02.05",
}

如何通过“datetime”使用NSMutableArray组并在uitableview中显示?

1 个答案:

答案 0 :(得分:0)

您可以为此推送自己的数据结构,但是TLIndexPathTools library会在您指定sectionNameKeyPath时自动对您的表进行分区,在这种情况下,这将是“datetime”。我在GitHub上提供了一个有关数据的工作示例。尝试运行JSON example project。视图控制器的完整源代码如下:

#import "TLTableViewController.h"

@interface JSONTableViewController : TLTableViewController
@end

#import "JSONTableViewController.h"
#import "TLIndexPathDataModel.h"

@implementation JSONTableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    //simulated JSON response as an array of dictionaries
    NSArray *jsonData = @[
        @{
            @"id": @(58),
            @"title": @"title59",
            @"summary": @"summary59",
            @"datetime": @"2013.02.03",
        },
        @{
            @"id": @(57),
            @"title": @"title58",
            @"summary": @"summary58",
            @"datetime": @"2013.02.04",
        },
        @{
            @"id": @(56),
            @"title": @"title57",
            @"summary": @"summary57",
            @"datetime": @"2013.02.04",
        },
        @{
            @"id": @(55),
            @"title": @"title56",
            @"summary": @"summary56",
            @"datetime": @"2013.02.05",
        }
    ];

    //initialize index path controller with a data model containing JSON data.
    //using "datetime" as the `sectionNameKeyPath` automatically groups items
    //by "datetime".
    self.indexPathController.dataModel = [[TLIndexPathDataModel alloc] initWithItems:jsonData
                                                            andSectionNameKeyPath:@"datetime"
                                                             andIdentifierKeyPath:@"id"];
}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dict = [self.indexPathController.dataModel itemAtIndexPath:indexPath];
    cell.textLabel.text = dict[@"title"];
    cell.detailTextLabel.text = dict[@"summary"];
}

@end