0

我从一个包含层次结构的 HTML 请求中得到一个 JSON 对象。

来自 JSON 对象的示例:

{
    "_id": "4f870f064f95ae0da8000002",
    "name": "Category",
    "parent_id": null
},
{
    "_id": "4f870f0e4f95ae0da8000004",
    "name": "Brand",
    "parent_id": null
},
{
    "_id": "4f8715bd4f95ae0da8000028",
    "name": "Dermalogica",
    "parent_id": "4f870f0e4f95ae0da8000004"
},
{
    "_id": "4f8715de4f95ae0da800002a",
    "name": "Molton Brown",
    "parent_id": "4f870f0e4f95ae0da8000004"
},
{
    "_id": "4f8715ea4f95ae0da800002c",
    "name": "Waxing",
    "parent_id": "4f870f064f95ae0da8000002"
},
{
    "_id": "4f8715f34f95ae0da800002e",
    "name": "Mens Hair",
    "parent_id": "4f870f064f95ae0da8000002"
},
{
    "_id": "4f8715fd4f95ae0da8000030",
    "name": "Ladies Hair",
    "parent_id": "4f870f064f95ae0da8000002"
},
{
    "_id": "4f87161f4f95ae0da8000032",
    "name": "Massage",
    "parent_id": "4f870f064f95ae0da8000002"
}

当我以相同的方式将它保存在一个实体中时,我将如何定义获取请求(排序)以便对象按照它们的父/子关系进行排序?

4

2 回答 2

0

无法使用 sortDescriptors 对此类数据进行排序。这就是我解决问题的方法,对带有线程样式讨论的文章发表评论。下载所有评论后,我需要reindexComments

-(void)reindexComments{
    NSArray *articleComments = self.comments.allObjects;
    [self fetchChildsWithComments:articleComments forParentId:0 num:1];
}

-(NSUInteger)fetchChildsWithComments:(NSArray*)articleComments forParentId:(NSUInteger)parentId num:(NSUInteger)num{
    NSArray *childComments = [articleComments filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"parentId == %u", parentId]];
    childComments = [childComments sortedArrayUsingComparator:^NSComparisonResult(Comment *c1, Comment *c2) {
        if (c1.commentIdValue < c2.commentIdValue){
            return NSOrderedAscending;
        }else{
            return NSOrderedDescending;
        }
    }];

    for (Comment *newRootComment in childComments){
        newRootComment.numValue = num;
        num++;
        num = [self fetchChildsWithComments:articleComments forParentId:newRootComment.commentIdValue num:num];
    }
    return num;
}

最后我只是按numValue字段排序以获得我很好的线程讨论

于 2014-02-27T19:00:20.017 回答
-1

一种方法 - 使用 NSOrderedSet - http://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSOrderedSet_Class/Reference/Reference.html

其次,更方便(因为在iOS 5中引入了NSOrderedSet),只是一个简单的带有sortDescriptors的NSFetchRequest。由于它是一个数组,你可以一次使用多个描述符。因此,使用parent_idid的描述符应该会给你想要的结果。

NSFetchRequest *request = [[NSFetchRequest alloc]init];
    request.entity = [NSEntityDescription entityForName:@"Child" inManagedObjectContext:context];
   // request.predicate = [NSPredicate predicateWithFormat:@"parent_id =  %@",parent_ID];You don't need any predicate,right?
    request.sortDescriptors = [NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"parent_id" ascending:YES],[NSSortDescriptor sortDescriptorWithKey:@"_id" ascending:YES],nil];

return [context executeFetchRequest:request error:&error];

而且,在 Objective-C 中,在名称中使用下划线并不方便。希望,这有帮助。

于 2012-04-12T23:00:14.110 回答