如何预取关系 NSManagedObject 的关系

Posted

技术标签:

【中文标题】如何预取关系 NSManagedObject 的关系【英文标题】:how to prefetch relationships of a relationship NSManagedObject 【发布时间】:2013-01-08 15:59:41 【问题描述】:

我正在搜索,需要加快速度。我有一系列汽车零件,我想找到有这些零件的汽车。这部分我做得很好。 NSManagedObject Cars.h

(cars 有一个名为 ToCarParts 的 NSSet,它列出了汽车的所有汽车零件)

NSMagagedObject Parts.h (Parts 有一个名为 ToCars 的 NSSet,它列出了与此相关的所有汽车)

//This takes all results gathered by using parts to search for car, and converts them to have the main object be a car
-(NSArray*)convertResultsToCars:(NSArray*)records
    NSMutableArray *manipulator =[NSMutableArray arrayWithArray:records];
    NSMutableArray *convertedArray =[[NSMutableArray alloc]init];

    for (int i=0; i<[manipulator count]; i++) 
        CarPart *FromManipulator=(CarPart*)[manipulator objectAtIndex:i];
        [convertedArray addObjectsFromArray:[[partFromManipulator toCars]allObjects]];
    

    NSLog(@"Results from core data = %i",[convertedArray count]);
    return [NSArray arrayWithArray:convertedArray];

当我从此处获取结果时,问题出现了,稍后必须在应用程序中加载所有 carParts。

Car *carResult =(Cars*)[resultsConvertedToCarsArray objectAtIndex:i];

        partsFromCar =[NSMutableArray arrayWithArray:[[carResult toParts]allObjects]];

如何在我的原始查询中预取上述信息,以便该信息已加载到对象中?

这是我最初的获取请求:

NSEntityDescription *entity = [NSEntityDescription entityForName:@"CarParts" inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:entity];
    [fetchRequest setPredicate:[self parseCarPartsIntoAPredicate:carPartsArray]];
    [fetchRequest setReturnsDistinctResults:YES];
    //I guess I would use something like this? but how would I structure it?
    [fetchRequest setRelationshipKeyPathsForPrefetching:@"I need to prefetch the toParts nsset of the cars found here (although in reality it brings up every instance of that car part, which I then have to convert into a car... something like found a car part, car for that part is a buick, what are the parts of the buick? ok, preload those parts"];

提前谢谢你!

【问题讨论】:

【参考方案1】:
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Post"];
[fetchRequest setRelationshipKeyPathsForPrefetching:@[@"Picture"]];

【讨论】:

【参考方案2】:

创建了一个 nsmanagedobject 来保存这些对象...

【讨论】:

以上是关于如何预取关系 NSManagedObject 的关系的主要内容,如果未能解决你的问题,请参考以下文章