如何正确保存到coredata一对多的关系

Jon*_*rft 3 iphone core-data objective-c ios

我很擅长保存到coreData并使用iOS开发.

我想要实现的目标:

我希望能够在我的数据库中拥有一个具有唯一标识符/的idFB用户,并且该用户可以创建和检索他们的工作例程.

我走了多远?

我设法(我认为)创建一个方法,正确地routineNameRoutine entity与右侧相关联的方法中检索User.看fetch方法.

我的问题:

我认为我没有与正确的实体关系协会保存User (usersExercise) <--->> Routine (userID).顺便说一下,我认为我的save方法不正确...因为我将整个用户保存到userID,它只是感觉不对?主要是因为当它吐出时它Routine.userID会拉动整个相关用户而不是特定ID?我真的不知道会发生什么

有谁可以帮我正确构建这些方法?我对coreData保存和建立正确关系的整个过程非常困惑.

在此输入图像描述

- (void) save {
    Routine *newRoutine = [NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:context];

    newRoutine.users = [self getCurrentUser];
    newRoutine.routineName = @"myRoutine Test Name";
    NSError* error;
    [context save:&error ];

    NSLog(@"Saved now try to fetch");
    [self fetch];

}
-(void) fetch {
    NSFetchRequest *fetchRequestItems = [[NSFetchRequest alloc] init];
    NSEntityDescription *entityItem = [NSEntityDescription entityForName:@"Routine" inManagedObjectContext:context];
    [fetchRequestItems setEntity:entityItem];
    User* user = [self getCurrentUser];
    // if i try [[self getCurrentUser] usersRoutine] it shows an error

    [fetchRequestItems setPredicate:[NSPredicate predicateWithFormat:@"users == %@",user]];

    //Sort by last edit ordered
    NSArray *sortDescriptors = [NSArray arrayWithObjects:nil];
    [fetchRequestItems setSortDescriptors:sortDescriptors];
    NSError *error = nil;
    NSArray* Routines = [context executeFetchRequest:fetchRequestItems error:&error];
    NSLog(@"result %@", [(Routine *)Routines[0] users]  );


}
-(User *)getCurrentUser {
    NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"User" inManagedObjectContext:context];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDesc];

    if (_appDelegate.isFB)
    { 
        request.predicate = [NSPredicate predicateWithFormat:@"idFB LIKE %@",_appDelegate.fdID];
        NSError *error = nil;
        NSArray *matches = [[context executeFetchRequest:request error:&error] mutableCopy];

        return (User *)matches[0];
    } else
    {
        NSLog(@"CreateRoutinePOPUP NON FB TO BE TESTED");
        request.predicate = [NSPredicate predicateWithFormat:@"email LIKE %@",_appDelegate.currentUser];
        NSError *error = nil;
        NSArray *matches = [[context executeFetchRequest:request error:&error] mutableCopy];

        return (User *)matches[0];
    }
Run Code Online (Sandbox Code Playgroud)

这是获取中的NSLog正在打印的内容:

2013-04-28 22:33:26.555 iGym[7916:c07] result <User: 0xa480580> (entity: User; id: 0xa495a00 <x-coredata://D87CEBB4-016C-4A1B-802C-2D1117BB3E51/User/p1> ; data: {
    dob = "1986-12-26 00:00:00 +0000";
    email = ".com";
    firstTime = nil;
    gender = male;
    height = nil;
    idFB =3333;
    idUserExternal = 0;
    idUserInternal = 0;
    isPT = nil;
    language = "en_US";
    location = "London, United Kingdom";
    metricSystem = nil;
    name = Joan;
    nickname = nil;
    password = nil;
    surname = Thurft;
    usersExercise = "<relationship fault: 0xa4824a0 'usersExercise'>";
    usersRoutine =     (
        "0xa495f00 <x-coredata://D87CEBB4-016C-4A1B-802C-2D1117BB3E51/Routine/p6>",
        "0xa4877e0 <x-coredata://D87CEBB4-016C-4A1B-802C-2D1117BB3E51/Routine/p1>",
        "0xa4877f0 <x-coredata://D87CEBB4-016C-4A1B-802C-2D1117BB3E51/Routine/p2>",
        "0xa487800 <x-coredata://D87CEBB4-016C-4A1B-802C-2D1117BB3E51/Routine/p3>",
        "0xa487810 <x-coredata://D87CEBB4-016C-4A1B-802C-2D1117BB3E51/Routine/p4>",
        "0xa487820 <x-coredata://D87CEBB4-016C-4A1B-802C-2D1117BB3E51/Routine/p5>"
    );
    weight = nil;
})
Run Code Online (Sandbox Code Playgroud)

当我添加NSLog时(@"获取当前结果%@",[(User*)匹配[0] usersRoutine]); 到getCurrentUser方法,我得到整个用户的数据和关系说

usersExercise = "<relationship fault: 0xa464730 'usersExercise'>";
Run Code Online (Sandbox Code Playgroud)

iwa*_*bed 7

核心数据与使用标准数据库完全不同,在标准数据库中,您可以将一些外键分配userID给另一个表,在该表中您希望与User对象建立关系,然后使用该外来ID来查找关系exercise.where('user_id = ?', userID).相反,您可以定义实际关系,并让Core Data处理幕后的所有内容,以设置任何连接表或外键.

而不是你如何把它设置了,你只需要在User实体两个关系exercisesroutines被映射到ExerciseRoutine实体,然后你必须在一个反比关系Exercise,并Routine呼吁users,如果它是一个具有-和belongs-多对多的关系.所以,现在,你需要更换usersExerciseexercises,usersRoutineroutines,然后userIDusersExerciseRoutine实体.

即使你实际上并不需要这种反向关系,你仍然需要它,因为Core Data将它用于数据完整性目的,如果你让它无人居住,Xcode会给你一个警告.

当您设置这些关系时,您将调用例程或练习user.exercises,这将返回该用户的相关练习集.正如您所注意到的,Core Data将返回他们称之为fault关系的内容,当您实际需要该关系的内容时,该关系将被触发并返回数据.存在故障,因此您只需返回所需的信息,而不是在数据集上运行不必要的查询.

另外需要注意的是,Core Data并不像userID您一样引用唯一ID .相反,Core Data中的每个对象都有一个唯一的ID [objectName objectID](在将其保存到数据存储后只是永久的).除特殊情况外,您实际上不需要在实体上设置唯一ID作为属性.

此外,你真的不需要使用那些独特objectID的,除非你像在多线程应用程序中传递对象进行后台处理,在这种情况下NSManagedObjectID是线程安全的,你可以用它来再次找到对象.后台线程/托管对象上下文.

我真的建议您阅读核心数据的介绍,例如http://www.raywenderlich.com/934/core-data-on-ios-5-tutorial-getting-started

如果您习惯于正常的数据库设置/架构,首次转换为Core Data可能有点奇怪,但是一旦习惯了它,它实际上要快得多,并为您处理幕后的所有艰苦工作.


评论更新:

你误解了核心数据中关系的概念.在Core Data中,关系不会像典型的数据库连接关系那样返回关联的ID.相反,它会返回一个错误,当您需要来自该关系的数据时会触发该错误.所以它不会返回整个User对象,而是返回fault到关联的User对象,当你执行类似操作时,它会被触发并查询exercise.user.name

你的代码的工作方式与保存时的代码完全相同,你只是在不正确的假设下.