Parse.com:按评论数量排序

时间:2014-08-25 16:41:27

标签: ios database parse-platform relation

我正在创建一个带帖子的UITableView。如果点击其中一个tableview的行,则会显示详细信息页面,其中可以对帖子进行评论。我正在使用Parse.com框架来实现这一点。

我在详细视图中保存了这样的评论:

PFObject *comment = [PFObject objectWithClassName:@"Comment"];
comment[@"content"] = _textViewComment.text;
comment[@"post"] = _object;
comment[@"user"] = currentUser;

[comment saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
    if(!error){
        UIAlertView* alertSave = [[UIAlertView alloc]initWithTitle:@"Saved" message:@"Your comment is saved" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertSave show];
        [self setToDefault:_textViewComment];
    }else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Warning" message:@"Comment not saved" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
}];

其中_object是当前帖子。

我现在要做的是按评论数量排序第一个tableview。但我只是从评论到帖子建立关系,而不是相反。

有没有办法查询帖子并按评论数量排序?

1 个答案:

答案 0 :(得分:0)

为此,您应该通过Post上的数组将评论与帖子相关联。

在Post上添加类型数组的“comments”col。当您获取帖子时,请在@“comments”键上使用includeKey :.然后更改您的更新代码以添加此类评论......

// in your code, I think "_object" is a post. calling it "post" here instead...

NSMutableArray *comments = [[post objectForKey:@"comments"] mutableCopy];
[comments addObject:comment];
[post setObject:comments forKey:@comments"];

// then save the post object.  parse will save the related comment.
[post saveInBackgroundWithBlock ...

仔细检查数据浏览器中的所有内容。然后,在下一次提取帖子后,您可以按评论计数排序......

[query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
    if (!error) {
        NSComparator comparator = ^(Post *postA, Post *postB) {
            NSNumber *countA = @([postA objectForKey:@"comments"].count);
            NSNumber *countB = @([postB objectForKey:@"comments"].count);
            return [countA compare:countB];
        };
        NSArray *sortedArray = [array sortedArrayUsingComparator:comparator];
        // use sortedArray as your tableview datasource
    }
}];