【发布时间】:2012-02-13 16:50:20
【问题描述】:
我是 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;
}
}
谢谢!这个超级基本的任务正在毁了我的星期天!
【问题讨论】: