核心数据一对多关系问题

时间:2013-03-14 07:47:24

标签: ios core-data nsmanagedobject nsmanagedobjectcontext nsentitydescription

我正在使用coreData一对多的关系。例如文件夹 - 文件。所以我想做的是从一个文件夹中取出一个文件并将其复制到另一个文件夹。

So for example 
folder   A  B
file     a  b
file     c  d

现在我想将文件夹c从文件夹A复制到文件夹B,它应该是这样的

folder A B
file   a b
file   c d
file     c

为了执行此操作,我编写了此代码 在某些导航操作

之后打开的某个View Controller中会发生这种情况

首先我在这里提取所有文件夹

 NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Folder" inManagedObjectContext:self.managedObjectContext];

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];
    NSError *error = nil;
    m_folderResults = [self.managedObjectContext executeFetchRequest:request error:&error];

然后我创建了一个新的文件实例

File *fileObject = [NSEntityDescription insertNewObjectForEntityForName:@"File" inManagedObjectContext:self.managedObjectContext];
    fileObject = (passed file object to this ViewController)

Folder *folderObject = [m_folderResults objectAtIndex:m_indexPath.row];

    NSMutableOrderedSet *files = [folderObject mutableOrderedSetValueForKey:@"file"];
    [files addObject:fileObject];

这是有效的,但我遇到的问题是我这样做了

folder A B
file   a b
file     d
file     c

意味着它将从一个文件夹中删除并添加到另一个文件夹中。

所以我想知道我哪里出错了。

此致 兰吉特

1 个答案:

答案 0 :(得分:1)

首先,根据您发布的代码,您将使用旧文件对象覆盖新创建的文件对象。当然,如果你在其他地方插入它,它将会从以前的位置消失。

其次,如果你想(1)真正复制文件c,你想要创建一个新实例并将其分配给另一个文件夹,或者如果你(2)只是想要让第二个文件夹也指向同一个文件(如果文件没有改变就有意义)。

对于案例(1),您必须

File *fileToBeCopied; 
Folder *destinationFolder;
File *newFile = [NSEntityDescription insertNewObjectForEntityForName:@"File" 
                          inManagedObjectContext:self.managedObjectContext];

// now you need to copy all the attributes of fileToBeCopied
// over to newFile

[destinationFolder addFileObject:newFile];
// or
newFile.folder = destinationFolder;

对于案例(2),请确保您的数据模型允许一个文件具有多个文件夹(多对多关系)。

[destinationFolder addFileObject:fileToBeCopied];
// or
[fileToBeCopied addFolderObject:destinationFolder];
相关问题