Objective c 使与一个对象的关系已存在

Objective c 使与一个对象的关系已存在,objective-c,core-data,entity-relationship,nsmanagedobject,Objective C,Core Data,Entity Relationship,Nsmanagedobject,用户必须在allfamile中创建族。在第二个视图中,用户必须在AllProduit中创建产品。创建时,用户必须选择之前创建的族 AllFamille和AllProduit是两个不同的实体。如何在他们之间建立关系 家庭创建: -(IBAction)save:(id)sender { app=[[UIApplication sharedApplication]delegate]; NSManagedObjectContext *context = [app managedObjec

用户必须在
allfamile
中创建族。在第二个视图中,用户必须在
AllProduit
中创建产品。创建时,用户必须选择之前创建的族

AllFamille
AllProduit
是两个不同的实体。如何在他们之间建立关系

家庭创建:

-(IBAction)save:(id)sender
{
    app=[[UIApplication sharedApplication]delegate];
    NSManagedObjectContext *context = [app managedObjectContext];
    AllFamille *famille = [NSEntityDescription insertNewObjectForEntityForName:@"AllFamille"inManagedObjectContext:context];        
    famille.name = nameFamField.text;   

    NSError *error;        
    if (![context save:&error]) {
        NSLog(@"Erroor");
    }

    [[NSNotificationCenter defaultCenter] postNotificationName:@"famCreated" object:self];
}
产品创造:

-(void)addProd:(NSString *)idProd    
{        
    NSManagedObjectContext *context = [app managedObjectContext];

    NSError *error = nil;

    AllCodeVente * _allCodeVente = (AllCodeVente*) [NSEntityDescription insertNewObjectForEntityForName:@"AllCodeVente" inManagedObjectContext:context];

    for (NSManagedObject *obj in app.cdeVenteArray)
    {
        _allCodeVente.codeVente = [obj valueForKey:@"cdv"];
        _allCodeVente.uniteVente = [obj valueForKey:@"uv"];            
    }

    AllProduit * _allProduit = (AllProduit*) [NSEntityDescription insertNewObjectForEntityForName:@"AllProduit" inManagedObjectContext:context];
    _allProduit.libelleProduit = nomStr;
    _allProduit.familleProduit=familleStr;
    _allProduit.stockProduit =qteStockStr;
    _allProduit.prixVenteProduit=prixVente;
    _allProduit.prixAchatProduit = prixAchat;
    _allProduit.idProduit= idProd;

    [_allCodeVente addProduitObject:_allProduit];        

    if (![context save:&error]) {
        NSLog(@"Erroor");
    }            
}

我不太确定我是否理解你的问题,但你可以遵循这些提示

以正确的方式为实体建模

这意味着(我想)您需要在
AllFamille
AF
)和
AllProduit
AP
)之间建立多对多的关系

例如,从
AF
AP
创建一个名为
toAllProduits
的对多关系。创建一个从
AP
AF
的名为
toallfamile
(逆)的关系

请参阅我的上一个答案:

检索正确的族

创建一组族后,您可以创建产品,并将其与特定族关联。怎么做

例如,创建一个
NSFetchRequest
来检索特定的
AF
。您需要一个
NSPredicate
。之后,只需使用检索到的族并将其指定给产品。e、 g

AllProduit * _allProduit = (AllProduit*) [NSEntityDescription insertNewObjectForEntityForName:@"AllProduit" inManagedObjectContext:context];
_allProduit.libelleProduit = nomStr;
// your other properties here...
_allProduit.toAllFamille = retrievedAllFamille; // where this object has been retrieved with the correct request
希望有帮助