iphone - 核心数据,一对多关系

标签 iphone ios ipad core-data

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

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

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

文章:

  • id文章
  • 正文
  • 类别(与类别的关系,逆=文章,最小可选,最大1)

类别:

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

当我添加一篇文章时。我首先惊讶的是不仅有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;
    }    
}

谢谢!这个 super 基本的任务目前毁了我的周日!

最佳答案

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

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

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

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

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

关于iphone - 核心数据,一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9250205/

相关文章:

ios - 如何使用解析 PFQuery 链接约束

iphone - 如何使用 NSPredicate 检索 NSArray 的索引?

iPhone 动画问题 SIMulator 与 Real Device

c# - Monotouch类

iphone - 如何在ios中编写web服务回调方法/类结构

javascript - 无法缩放我的 iPad 应用程序

ipad - swift iPad 表格 View 不透明

ios - 重新连接到断开连接的对等体

iphone - [[CAShapeLayer alloc] init] 和 [CAShapeLayer layer] 的区别

ios - 无法在 UIView 中将 UITextField 居中