【问题标题】:ios NSFetchRequest, order child objectsios NSFetchRequest,订购子对象
【发布时间】:2011-04-17 13:09:18
【问题描述】:

您好想知道如何指定一个 FetchRequest,我可以在其中对关系中的对象进行排序。

   |  Parent         |        | Child        |
   |     - name      |------->|   - name     |
   |     - position  |        |   - position |

例如,如果我有一个包含位置属性的父表,并且与具有一个也具有位置属性的子表具有一对多关系。如何返回包含按位置排序的子对象的父对象(按位置排序)。

例如

parent 1
   child 1
   child 2
   child 3

parent 2
   child 15
   child 16

parent 3
   child 22
   child 23
   child 24

显然,下面的代码将正确排序父对象,但是我如何使每个父对象返回的子对象的顺序正确

    NSFetchRequest* fetchReqest = [[NSFetchRequest alloc] init];

    NSEntityDescription* entity = [NSEntityDescription entityForName:@"parent"  inManagedObjectContext:managedObjectContext];
    [fetchReqest setEntity:entity];  

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
                                        initWithKey:@"position" ascending:YES];
    [fetchReqest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    [sortDescriptor release];

    NSArray* parentsThatContainChildren =  [managedObjectContext executeFetchRequest:fetchReqest error:nil];

干杯

【问题讨论】:

    标签: ios core-data nsfetchrequest nssortdescriptor


    【解决方案1】:

    有两种策略:

    1. 使用 NSSortDescriptor 为子项执行单独的提取请求。 Pro:你把它保存在 FetchController 中。缺点:多个 fetch 请求会减慢您的速度
    2. 在 NSArray* parentsThatContainChildren 中对返回的孩子进行排序。

    对于#2,你可以check this out

    NSSortDescriptor *positionSort = [NSSortDescriptor sortDescriptorWithKey:@"position" ascending:YES];
    
    NSArray *children = [[parent.children allObjects] sortedArrayUsingDescriptors:[NSArray arrayWithObject:positionSort]];
    

    【讨论】:

    • 太棒了。感谢您的帮助。
    • 第二种策略很好。感谢您的建议!
    猜你喜欢
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多