【问题标题】:Parse.com: Sort by number of commentsParse.com:按评论数量排序
【发布时间】:2014-08-25 16:41:26
【问题描述】:

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

我将这样的 cmets 保存在 detailview 中:

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 是当前帖子。

我现在要做的是按 cmets 的数量对第一个 tableview 进行排序。但我只是在评论与帖子之间建立关系,而不是相反。

有没有办法查询帖子并按 cmets 的数量对其进行排序?

【问题讨论】:

  • 能把查询帖子的代码贴出来(_object)吗?
  • 我在tableview所在的第一个视图控制器中查询它:PFQuery postQuery = [PFQuery queryWithClassName:@"Post"]; [postQuery includeKey:@"author"]; [postQuery orderByDescending:@"updatedAt"]; [postQuery findObjectsInBackgroundWithTarget:self 选择器:@selector(callBack:)];然后回调: - (void)callBack:(NSArray)array{ memoires = array; [tableViewMemoires reloadData]; } 然后我用 didSelectRowAtIndexPath 将它传递给下一个视图控制器

标签: ios database parse-platform relation


【解决方案1】:

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

在 Post 上添加一个数组类型的“cmets”col。当您获取帖子时,请在 @"cmets" 键上使用 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
    }
}];

【讨论】:

  • 当我这样做时,saveInBackGroundWithBlock 不再被调用
  • 调用一定是有错误的,能不能在检查错误前设置断点?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-21
  • 1970-01-01
  • 1970-01-01
  • 2016-03-18
  • 2021-10-05
  • 1970-01-01
  • 2013-02-18
相关资源
最近更新 更多