2012-07-16 81 views
0

同時在代碼中創建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; 
} 

回答

1

如果你真的想這樣做的代碼,你必須創建一個NSRelationshipDescription,並把它添加到源對象的屬性。

這裏是doc

在分配對象之前創建對象並調用setMaxCount:。如果你看一下在isToMany方法的文檔,你會看到,它說:

YES if the receiver represents a to-many relationship (its maxCount is greater than 1) otherwise NO.

+0

是我知道我必須補充NSRelationshipDescription但由於一對多的屬性是隻讀的,我不能讓1對多的關係。請幫我或爲我寫一個示例代碼。非常感謝 – user1266375 2012-07-17 05:36:55

相關問題