0

我想与 Core Data 中的两个实体建立基本关系,但这种关系要么没有保存,要么工作不正常,我不知道为什么。

这两个实体是CharacterAvatar,它是一对一的关系。一个角色可以有 1 个头像。从技术上讲,它应该是“一个头像可以被多个角色拥有”,但我稍后会处理。

我想添加角色并为他们分配头像。

Core Data 中已经有 10 个头像和 1 个角色,这两个我都通过终端和 SQLite 进行了验证。

问题是,我遇到了麻烦“通过名称查找头像,然后将关系保存到角色”。

至今,

我设置了一个名为:“frqAvatarWithName”的获取请求,其中 Predicate 具有以下结构:

[引用]

名称 == $AVATAR_NAME

[/引用]

就是这样:我可以找到一个具有特定名称的头像;然后我可以与角色建立关系。

问题 1:它开始执行查询,但从不显示有多少记录。

我在调试模式下遇到EXC_BAD_ACCESS错误,我已将其追溯到获取请求模板处理 - 所以,这一定是错误的,或者我做错了。

问题 2:我不确定我是否正确设置了这种“基本”关系。

[代码]

// This code is meant to find an avatar with a certain name and then save the relationship
// between a character and said avatar.
// This is my app delegate file for the moment
// All the files are present, and I have deleted/recreated the app various times
-(void)characterMaker
{
    NSLog(@"Inside characterMaker...");
    NSError *error = nil;
    NSManagedObjectContext *context = [self managedObjectContext];
    NSManagedObjectModel *model = [self managedObjectModel];

    // Find an avatar with a specific name
    NSString *nameToFind = @"avt_player_1";


    // Use a Fetch request template
    NSDictionary *subs = [NSDictionary dictionaryWithObjectsAndKeys:nameToFind, @"AVATAR_NAME", nil];
    NSFetchRequest *fetchRequest = [model fetchRequestFromTemplateWithName:@"frqAvatarWithName" 
                                              substitutionVariables:subs];


    // Set the entity to use
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Avatar"
                                              inManagedObjectContext:context];


    [fetchRequest setEntity:entity];

    // Execute the query (it never even reaches this point)
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];

    if (fetchedObjects == nil) {
        // Handle the error
        NSLog(@"Error -- %@", [error localizedDescription]);
        abort();
    }

    NSLog(@"Found %@ records", [fetchedObjects count]);

// Print out avatar names
    for (Avatar *a in fetchedObjects)
    {
        NSLog(@"Name = %@", [a valueForKey:@"name"]);
    }

    // This is where I would use `a` and store it in a character entity, and thus create the relationship

[/代码]

4

1 回答 1

0

我放弃了这个,用 FMDatabase 项目和 SQLite 完成了整个项目;我已经能够以这种方式解决问题。

线程关闭。

于 2011-01-04T10:10:09.237 回答