0

我正在尝试将托管对象从源持久存储到现有持久存储执行“深度复制”。借用任务代码以在目标上下文中建立多对多关系。完整的代码在这里

我的困惑在于下面的方法

- (void)establishToManyRelationship:(NSString*)relationshipName
                         fromObject:(NSManagedObject*)object // “Copied Object" in TargetContext
                      withSourceSet:(NSMutableSet*)sourceSet // NSMutableSet in Source Context.
{
    if (!object || !sourceSet || !relationshipName) {
        NSLog(@"SKIPPED establishing a To-Many relationship from %@", [self objectInfo:object]);
        NSLog(@"Due to missing Info!");
        return;
    }

    //  Returns a mutable set proxy that provides read-write access to the unordered to-many relationship specified by a given key.
    NSMutableSet *copiedSet =[object mutableSetValueForKey:relationshipName];

    //in sourceContext, "Many"side of relationship represented by a Set, where "relatedObject" belongs to
    for (NSManagedObject *relatedObject in sourceSet) {

        // Related Copied Object in TargetContext
        NSManagedObject *copiedRelatedObject =
            [self copyUniqueObject:relatedObject toContext:object.managedObjectContext];

        if (copiedRelatedObject) {
            [copiedSet addObject:copiedRelatedObject];
            NSLog(@"A copy of %@ is now related via To-Many '%@' relationship to %@", [self objectInfo:object],
                  relationshipName,
                  [self objectInfo:copiedRelatedObject]);
        }
    }
    // REMOVE the relationship from memory after it is committed to disk
    [CoreDataImporter saveContext:object.managedObjectContext];

    [object.managedObjectContext refreshObject:object mergeChanges:NO];
}

我的问题是,之后

[copiedSet addObject:copiedRelatedObject];

,这是在“集合代理对象”(由mutableSetValueForKey:调用产生)上执行的,并且没有从此方法返回结果(明确地通过参数或返回值)

- (void)establishToManyRelationship:(NSString*)relationshipName
                         fromObject:(NSManagedObject*)object 
                      withSourceSet:(NSMutableSet*)sourceSet

,如何确保在目标上下文中创建了一个 NSMutableSet(由复制相关对象组成)?或者我永远不需要在目标上下文中引用此类“复制集”?目标上下文中的对象图是否可以通过使用通过 KVC 实现的“集合代理对象”围绕“复制对象”(代表“多对多”关系的 ONE 端)神奇地建立?

4

1 回答 1

0

After a few testings, I figured it out.

The 2nd parameter "(NSManagedObject*)object" can be manipulated via the proxy (NSMutableSet *copiedSet), which is returned by KVC invocation on "mutableSetValueForKey:".

Any operations loaded on the proxy, will magically/actually reflect back on the relationships of "(NSManagedObject*)object" (as this MO's properties).

于 2014-09-23T00:06:20.827 回答