使用分组将对象添加到 NSMutable 数组 [英] Add objects to NSMutable array with grouping

查看:20
本文介绍了使用分组将对象添加到 NSMutable 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的 NSArray sampleData 接收来自 parse.com 数据库的实际数据,假设如下:

I want my NSArray sampleData to receive actual data from parse.com database assuming like this:

self.sampleData = @[ @{ @"date": @"12/5/2014",
                        @"group": @[ @{ @"text": @"post1", @"location": @"x,y" },
                                     @{ @"text": @"post2", @"location": @"x,y" },
                                     @{ @"text": @"post3", @"location": @"x,y" },
                                     @{ @"text": @"post4", @"location": @"x,y" },
                                     @{ @"text": @"post5", @"location": @"x,y" }
                                   ]
                        },
                     @{ @"date": @"12/3/2014",
                        @"group": @[ @{ @"text": @"post6", @"location": @"x,y" },
                                     @{ @"text": @"post7", @"location": @"x,y" },
                                     @{ @"text": @"post8", @"location": @"x,y" },
                                     @{ @"text": @"post9", @"location": @"x,y" },
                                     @{ @"text": @"post10", @"location": @"x,y" }
                                   ]
                        }
                  ];

如您所见,我想按日期对文本和位置进行分组,以便我可以在以日期为标题和文本/位置为内容的视图中显示它们.以下是我目前能够做的事情:

As you can see, I want to group text and location by date, so that I can display them in a view with date as header and text/location as content. Here below is what I'm capable doing so far:

PFQuery *postQuery = [PFQuery queryWithClassName:kPAWParsePostsClassKey];
[postQuery whereKey:kPAWParseUserKey equalTo:[PFUser currentUser]];

postQuery.cachePolicy = kPFCachePolicyNetworkElseCache;
postQuery.limit = 20;

[postQuery findObjectsInBackgroundWithBlock:^(NSArray *myPosts, NSError *error)
 {
     if( !error )
     {

         NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
         [formatter setDateFormat:@"MM/dd/yyyy"]; 

         NSMutableArray *objectArray = [NSMutableArray new];

         for (PFObject *object in myPosts) {
             [objectArray addObject:@{@"createdAt": [formatter stringFromDate:object.createdAt], @"text": [object objectForKey:@"text"], @"location": [object objectForKey:@"location"]}];
         }

         self.sampleData = objectArray;
         NSLog(@"My sampleData --> %@", self.sampleData);

     }
 }
];

上面的代码很明显没有任何分组,所以在这里真的需要帮助.

The above code is obvious there's no grouping whatsoever, so really need help here.

推荐答案

好的,您有一个项目数组,并且您想根据特定键将它们分组到多个部分中.

Okay, so you have an array of items, and you want to group them into sections based on a particular key.

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM/dd/yyyy"];

// Sparse dictionary, containing keys for "days with posts"
NSMutableDictionary *daysWithPosts = [NSMutableDictionary dictionary];

[myPosts enumerateObjectsUsingBlock:^(PFObject *object, NSUInteger idx, BOOL *stop) {

    NSString *dateString = [formatter stringFromDate:[object createdAt]];

    // Check to see if we have a day already.
    NSMutableArray *posts = [daysWithPosts objectForKey: dateString];

    // If not, create it
    if (posts == nil || (id)posts == [NSNull null])
    {
        posts = [NSMutableArray arrayWithCapacity:1];
        [daysWithPosts setObject:posts forKey: dateString];
    }

    // add post to day
    [posts addObject:obj];
}];

// Sort Dictionary Keys by Date
NSArray *unsortedSectionTitles = [daysWithPosts allKeys];
NSArray *sortedSectionTitles = [unsortedSectionTitles sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSDate *date1 = [formatter dateFromString:obj1];
    NSDate *date2 = [formatter dateFromString:obj2];
    return [date2 compare:date1];
}];

NSMutableArray *sortedData = [NSMutableArray arrayWithCapacity:sortedSectionTitles.count];

// Put Data into correct format:
[sortedSectionTitles enumerateObjectsUsingBlock:^(NSString *dateString, NSUInteger idx, BOOL *stop) {
    NSArray *group = daysWithPosts[dateString];
    NSDictionary *dictionary = @{ @"date":dateString,
                                  @"group":group };
    [sortedData addObject:dictionary];
}];

self.sampleData = sortedData;

此代码不会完全生成您要求的内容.它将生成如下所示的内容:

This code will not generate exactly what you asked for. It will generate something that looks like this:

sampleData = @[ @{ @"date": @"12/5/2014",
                    @"group": @@[ PFObject*,
                                 PFObject*,
                                 PFObject*,
                                 PFObject*,
                                 PFObject*,
                               ]
                    },
                 @{ @"date": @"12/3/2014",
                    @"group": @[ PFObject*,
                                 PFObject*,
                                 PFObject*,
                                 PFObject*,
                                 PFObject
                               ]
                    }
              ];

无需将 myPosts 数组中的 PFObject* 转换为 @{ @"text": @"post5", @"location":@"x,y" } 因为您将无法访问其他信息.下面是如何使用这个 sampleData 数组.

There's no need to convert your PFObject* in the myPosts array into @{ @"text": @"post5", @"location": @"x,y" } since you'll lose access to other pieces of information. Here is how you would use this sampleData array.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; {
    return self.sampleData.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section; {
    return self.sampleData[section][@"date"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; {
    return self.sampleData[section][@"group"].count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; {

    PFObject *post = self.sampleData[indexPath.section][@"group"][indexPath.row];
    UITableViewCell *cell = // dequeue A reusable tableviewcell here

    // configure the cell here

    return cell;
}

这篇关于使用分组将对象添加到 NSMutable 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆