【问题标题】:Add objects to NSMutable array with grouping通过分组将对象添加到 NSMutablearray
【发布时间】:2014-12-05 13:55:30
【问题描述】:

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

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

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

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);

     }
 }
];

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

【问题讨论】:

  • 我遇到过this,它似乎与我的问题非常接近,但我仍然无法理解。
  • myPosts中的数据是什么格式的?
  • 这是 Parse.com 上的数据。它看起来像这样:objectId(string), location(GeoPoint), text(String), createdAt(Date), ...
  • 只是为了给你我想要做的事情,请参阅link。这正是我想要显示我的数据,但我一直坚持如何用 Parse.com 的实际数据替换 sampleData。
  • 我不熟悉 Parse。你可以记录NSLog(@"%@",myPosts); 并复制输出吗?我怀疑数据的格式已经正确。

标签: objective-c parse-platform nsmutablearray nsdictionary pfquery


【解决方案1】:

好的,所以您有一个项目数组,并且您希望根据特定键将它们分组到部分中。

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;

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

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 数组。

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

【讨论】:

  • 您是否也可以帮助制作文本和位置的键,至少用于实验?我试过你的代码,但我的表格视图什么也没显示。我只是想知道是否需要这些键,因为原始 sampleData 有一个文本键。不过我非常喜欢你的代码。
  • 我已经为文本创建了一个密钥来进行实验,但它仍然无法正常工作。我会花更多时间深入研究它。反正我已经接受了你的回答。非常感谢。
  • @SanitLee 在这一点上,我认为精通Parse 的人可以为您提供比我更多的帮助。
  • 终于找到了解决办法。只需在我的 findObjectsInBackgroundWithBlock 内的主线程上刷新表视图。再次感谢@StephenFurlani
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-28
  • 2012-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-22
  • 1970-01-01
相关资源
最近更新 更多