核心数据,一对多关系

发布于 2025-01-04 15:17:12 字数 3279 浏览 3 评论 0原文

我是 iOS 开发新手,正在使用核心数据进行一些测试。一切都很好,直到我开始玩弄关系。 在上下文中:

我有 2 个实体:文章和类别。

Article 有两个成员 idArticle 和 text。文章必须有一个类别。 Category 有两个成员 idCategory 和 name。类别可以有 0 篇或多篇文章。

文章:

  • idArticle
  • 文本
  • 类别(与类别的关系,反向 = 文章,最小可选,最大 1)

类别:

  • idCategory
  • 名称
  • 文章(与文章的多个关系,反向 = 类别,最小可选,最大无限制)

当我添加一篇文章时。我首先惊讶的是不仅有article1.category,还有article1.idCategory和article1.name! 我目前已将所有属性、关系设置为可选。 无论我做什么,当我使用下面的代码添加一篇新文章时,如果我不设置article.idCategory和article.name,它也会添加一个新类别,其中将包含idCategory = 0和name = nil!或者如果我设置它们则为相应的值。但是,我不希望它创建该类别,我只想添加一个现有类别。 Article.category 工作正常;它将文章添加到正确的类别!如果我只设置article.category; article.idCategory = 0 且article.name = nil。

我想我可以删除新创建的类别,但我希望我的代码整洁。我在网上搜索过,但没有找到与该问题类似的示例。我在这里不处理任何 GUI。 我的代码:

 - (BOOL)createNewGmtArticle:(NSNumber*)articleID title:(NSString*)paramTitle text:(NSString*)paramText date:(NSDate*)paramDate categoryID:(NSNumber*)paramCategoryID categoryName:(NSString*)paramCategoryName

{
    GasMattersTodayArticles *gmtArticle = [NSEntityDescription insertNewObjectForEntityForName:@"GasMattersTodayArticles" inManagedObjectContext:self.managedObjectContext]; // Look the given entitiy GasMattersTodayArticles in the given managed obj context

    if(gmtArticle != nil)
    {
        // Fill article
        gmtArticle.idArticle = articleID;
        gmtArticle.text = paramText;

        gmtArticle.category = [self getGmtCategoryWithId:paramCategoryID];
        //gmtArticle.idCategory = gmtArticle.category.idCategory; 
        //gmtArticle.name = gmtArticle.category.name;        

        NSError *savingError = nil;
        if([self.managedObjectContext save:&savingError]) // flush all unsaved data of the context to the persistent store
        {
            NSLog(@"Successfully saved the context");
            return YES;
        }
        else
        {
            NSLog(@"Failed to save the context. Error = %@", savingError);
            return NO;
        }
    }

    NSLog(@"Failed to create the new article");
    return NO;
}

谢谢

-(GasMattersTodayCategory *)getGmtCategoryWithId:(NSNumber*)categoryID

{
    // Create the fetch request first
    NSDictionary *subs = [NSDictionary dictionaryWithObject:categoryID forKey:@"SEARCH_KEY"];    
    NSFetchRequest *fetchRequest = [self.managedObjectModel fetchRequestFromTemplateWithName:@"CategoryWithKey" substitutionVariables:subs];
    // Entity whose contents we want to read
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"GasMattersTodayCategory" inManagedObjectContext:self.managedObjectContext];

    // Tell the request that we want to read the content of the person entity
    [fetchRequest setEntity:entity];

    // Excecute the fetch request on the context
    NSError* requestError = nil;
    GasMattersTodayCategory *category = [[self.managedObjectContext executeFetchRequest:fetchRequest error:&requestError] lastObject];

    // Make sur we get a category
    if(category != nil)
    {
        return category;
    }
    else
    {
        NSLog(@"Could not find any Category entities with this Id in the context.");
        return nil;
    }    
}

!这个超级基本的任务现在毁了我的周日!

I new to iOS development and doing some test with the core data. It was all fine until I started playing with relationship.
In context:

I have 2 entity: Article and Category.

Article has two members idArticle and text. Articles has to have a single Category.
Category has two members idCategory and name. Category can have 0 or several Articles.

Article:

  • idArticle
  • text
  • category (Relationship to Category, Inverse = articles, minimum optional, maximum 1)

Category:

  • idCategory
  • name
  • articles (To many Relationship to Article, Inverse = category, minimum optional, maximum unlimited)

While I am adding an article. I am first surprise to not only have article1.category but also article1.idCategory and article1.name!
I have currently set all my attributes, relationship to optional.
Whatever I do, when I add a new article using the code below, it will add a new Category as well which will contain idCategory = 0 and name = nil if I dont set article.idCategory and article.name! or to the corresponding value if I set them. However, I don't want it to create that category, I just want to add an existing category.
article.category works fine; it add the article to the right category! If I only set article.category; article.idCategory will = 0 and article.name = nil.

I suppose that I could delete the newly created category but I want my code to be neat. I have search the web but didnt find similar example with that problem. I am not dealing with any GUI here.
My code:

 - (BOOL)createNewGmtArticle:(NSNumber*)articleID title:(NSString*)paramTitle text:(NSString*)paramText date:(NSDate*)paramDate categoryID:(NSNumber*)paramCategoryID categoryName:(NSString*)paramCategoryName

{
    GasMattersTodayArticles *gmtArticle = [NSEntityDescription insertNewObjectForEntityForName:@"GasMattersTodayArticles" inManagedObjectContext:self.managedObjectContext]; // Look the given entitiy GasMattersTodayArticles in the given managed obj context

    if(gmtArticle != nil)
    {
        // Fill article
        gmtArticle.idArticle = articleID;
        gmtArticle.text = paramText;

        gmtArticle.category = [self getGmtCategoryWithId:paramCategoryID];
        //gmtArticle.idCategory = gmtArticle.category.idCategory; 
        //gmtArticle.name = gmtArticle.category.name;        

        NSError *savingError = nil;
        if([self.managedObjectContext save:&savingError]) // flush all unsaved data of the context to the persistent store
        {
            NSLog(@"Successfully saved the context");
            return YES;
        }
        else
        {
            NSLog(@"Failed to save the context. Error = %@", savingError);
            return NO;
        }
    }

    NSLog(@"Failed to create the new article");
    return NO;
}

and

-(GasMattersTodayCategory *)getGmtCategoryWithId:(NSNumber*)categoryID

{
    // Create the fetch request first
    NSDictionary *subs = [NSDictionary dictionaryWithObject:categoryID forKey:@"SEARCH_KEY"];    
    NSFetchRequest *fetchRequest = [self.managedObjectModel fetchRequestFromTemplateWithName:@"CategoryWithKey" substitutionVariables:subs];
    // Entity whose contents we want to read
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"GasMattersTodayCategory" inManagedObjectContext:self.managedObjectContext];

    // Tell the request that we want to read the content of the person entity
    [fetchRequest setEntity:entity];

    // Excecute the fetch request on the context
    NSError* requestError = nil;
    GasMattersTodayCategory *category = [[self.managedObjectContext executeFetchRequest:fetchRequest error:&requestError] lastObject];

    // Make sur we get a category
    if(category != nil)
    {
        return category;
    }
    else
    {
        NSLog(@"Could not find any Category entities with this Id in the context.");
        return nil;
    }    
}

Thanks! This super basic task is currently ruining my sunday!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

倾`听者〃 2025-01-11 15:17:12

最有可能发生这种情况的情况是,如果您的文章实体是类别的子类。

否则,当设置 gmtArticle.idCategory 时,您会收到异常,告诉您 GasMattersTodayArticlesidCategory 的键值不兼容。

GasMattersTodayArticlesGasMattersTodayCategory 都应该是 NSManagedObject 的子类(或者可能是您项目的基类)。

创建文章时您正在创建一个新类别,因为根据您的结构,文章类别。

然而,如果没有看到.xcdatamodel,这个答案只是一个猜测。

The most likely way this could have happened is if your Article Entity is a sub-class of Category.

You would get exceptions otherwise when setting gmtArticle.idCategory telling you that GasMattersTodayArticles is not key-value compliant to idCategory.

GasMattersTodayArticles and GasMattersTodayCategory should both be sub-classes of NSManagedObject (or maybe a base class for your project).

You are creating a new category when you create an article because according to your structure an Article is-a Category.

However without seeing the .xcdatamodel this answer is a guess.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文