核心数据 - 父/子层次结构的排序描述符

时间:2012-04-12 19:52:43

标签: ios core-data nsfetchedresultscontroller nsfetchrequest

我从包含层次结构的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"
}

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

2 个答案:

答案 0 :(得分: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字段排序以获得我的精彩线程讨论

答案 1 :(得分:-1)

单向 - 使用NSOrderedSet - http://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSOrderedSet_Class/Reference/Reference.html

第二,更方便(因为在iOS 5中引入了NSOrderedSet),只是一个带有sortDescriptors的简单的NSFetchRequest。因为它是一个数组,你可以根据需要一次使用多个descritor。因此,使用 parent_id id 的描述符可以为您提供所需的结果。

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中,在名称中使用下划线并不方便。 希望,这有帮助。