首页 文章

核心数据获取一对多关系数据

提问于
浏览
4

我已经四处寻找,但我仍然不清楚我希望有人为我澄清的各种概念 .

当我试图在尊重某种用户ID的同时保存到Exercise / Routine实体中时,我会感到困惑和头疼 .

为了理解和阅读核心数据,我设置核心数据的方式,它应该工作,能够拉动和保存信息到常规和练习,同时尊重他们正在使用的用户 . 如果我错了,有人可以纠正我吗?

我想我必须做一个类似的查询(用SQL术语)

INSERT INTO Routine (Values) WHERE Routine.userID = user.usersExercise

那是对的吗?如果这是正确的 . 现在我的问题是我不知道如何在coreData代码中 Build 这两个实体的内连接,以便生成这样的查询 .

任何帮助都非常感谢!

enter image description here

1 回答

  • 3

    是的,您需要使用NSPredicate来获取与特定用户相关的数据 . 如果您正在填充UICollection视图,那么我建议您也阅读NSFetchedResultsController .

    NSFetchRequest *fetchRequestItems = [[NSFetchRequest alloc] init];
    NSEntityDescription *entityItem = [NSEntityDescription entityForName:@"Routine" inManagedObjectContext:self.managedObjectContext];
    [fetchRequestItems setEntity:entityItem];
    
    User* myUser = //Code for getting current user out of data store based on some paramator
    [fetchRequestItems setPredicate:[NSPredicate predicateWithFormat:@"userID == %@",myUser]];
    
    //Sort by last edit ordered
    NSArray *sortDescriptors = [NSArray arrayWithObjects:nil];
    [fetchRequestItems setSortDescriptors:sortDescriptors];
    
    NSArray* Routines = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
    

    这里需要注意的是,您需要在Routine / Exercise对象上设置反向关系,以与谓词中的当前用户进行比较 . 对于我认为是反向关系的userID你有哪些?

    所以从评论中我没有设置反比关系,所以这里是一个粗略的例子 .

    在您的商店中制作新用户时,您会得到这样的信号:

    User *thisUser = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:self.managedObjectContext];
    
    thisUser.eMail = emailAddress.text;
    //And any other paras you might have
    

    然后在为该用户创建例程时,您将执行以下操作:

    Routine *newRoutine = [NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];
    
    newRoutine.userId = thisUser;
    

    然后确保保存托管对象以将更改写入数据存储 . 然后,这将链接例程端的2个对象,不要忘记在用户端链接它以获得严格的反向关系 .

    为了让用户完全像我上面提到的那样:

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"User" inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];
    
    NSError* error;
    NSArray* Users = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
    

    如果你有1个用户,那么它是数组中的第一个元素,如果你有很多用户,那么使用谓词根据你的FB id找到一个 .

相关问题