使用coredata中的代码创建两个实体之间的关系iPhone
问题描述:
同时在代码中创建ManageObjectModel我创建两个实体及其属性。但问题是我如何能够创建关系到两个实体之间的许多关系。我的代码如下。 我只是想使用代码在两个员工和组织实体之间建立一对多的关系。使用coredata中的代码创建两个实体之间的关系iPhone
- (NSManagedObjectModel *)managedObjectModel
{
if (__managedObjectModel != nil) {
return __managedObjectModel;
}
__managedObjectModel = [[NSManagedObjectModel alloc] init];
NSEntityDescription *employeeEntity = [[NSEntityDescription alloc] init];
[employeeEntity setName:@"Employee"];
[employeeEntity setManagedObjectClassName:@"Employee"];
NSEntityDescription *organizationEntity = [[NSEntityDescription alloc] init];
[organizationEntity setName:@"Organization"];
[organizationEntity setManagedObjectClassName:@"Organization"];
[__managedObjectModel setEntities:[NSArray arrayWithObjects:employeeEntity, organizationEntity, nil]];
NSAttributeDescription *nameAttribute = [[NSAttributeDescription alloc] init];
[nameAttribute setName:@"name"];
[nameAttribute setAttributeType:NSDateAttributeType];
[nameAttribute setOptional:NO];
NSAttributeDescription *idAttribute = [[NSAttributeDescription alloc] init];
[idAttribute setName:@"id"];
[idAttribute setAttributeType:NSInteger32AttributeType];
[idAttribute setOptional:NO];
NSArray *properties = [NSArray arrayWithObjects: nameAttribute, idAttribute, nil];
[employeeEntity setProperties:properties];
NSAttributeDescription *organizationNameAttribute = [[NSAttributeDescription alloc] init];
[organizationNameAttribute setName:@"Name"];
[organizationNameAttribute setAttributeType:NSStringAttributeType];
[organizationNameAttribute setOptional:NO];
properties = [NSArray arrayWithObjects:organizationNameAttribute, nil];
[organizationEntity setProperties:properties];
return __managedObjectModel;
}
答
如果你真的想这样做的代码,你必须创建一个NSRelationshipDescription
,并把它添加到源对象的属性。
这里是doc。
在分配对象之前创建对象并调用setMaxCount:
。如果你看一下在isToMany
方法的文档,你会看到,它说:
YES if the receiver represents a to-many relationship (its maxCount is greater than 1) otherwise NO.
是我知道我必须补充NSRelationshipDescription但由于一对多的属性是只读的,我不能让1对多的关系。请帮我或为我写一个示例代码。非常感谢 – user1266375 2012-07-17 05:36:55