2010-03-13 73 views
0

我在我的应用程序中使用核心数据。我有两个相关的实体:EntityA和EntityB。 EntityA具有与EntityB类型“关系”的属性。另外,这两个实体都是定义的类(不是默认的NSManagedObject)。我正在向我的数据中插入一个新对象,如下所示:iPhones SDK:使用核心数据设置关系属性对象?

EntityA *newEntityA = [NSEntityDescription insertNewObjectForEntityForName:@"EntityA" inManagedObjectContext:self.managedObjectContext]; 

newEntityA.name = @"some name"; 
newEntityA.entityB.name = @"some other name"; 

问题是entityB.name为null。即使我在赋值后立即添加一条NSLog()语句,它也是null。当EntityB是EntityA的属性时,设置EntityB的“名称”属性的正确方法是什么?

回答

1

您还需要首先创建一个EntityB对象:

EntityA *newEntityA = [NSEntityDescription insertNewObjectForEntityForName:@"EntityA" inManagedObjectContext:self.managedObjectContext]; 

newEntityA.name = @"some name"; 

EntityB *newEntityB = [NSEntityDescription insertNewObjectForEntityForName:@"EntityB" inManagedObjectContext:self.managedObjectContext]; 

newEntityA.entityB = newEntityB; 
newEntityA.entityB.name = @"some other name"; 
+0

谢谢。有时候,这是摆脱我们的显而易见的事情。 – memmons 2010-03-14 18:23:35