0

用户必须在 中创建一个族AllFamille。在第二个视图中,用户必须在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");
    }            
}
4

1 回答 1

1

我不太确定我是否理解您的问题,但您可以按照这些提示进行操作。

以正确的方式为您的实体建模

AllFamille这意味着您需要(我想) (AF为简洁起见)和AllProduit( )之间的一对多关系AP

例如,创建一个名为toAllProduitsfrom AFto的一对多关系AP。创建一个名为toAllFamille(逆)的关系 from APto AF

请参阅我的上一个答案:在 Core Data 中建立父子关系

检索正确的家庭

在创建了一堆系列之后,您可以创建产品并将它们与特定系列相关联。如何?

例如,创建一个NSFetchRequest来检索特定的AF. 您将需要一个NSPredicate. 之后,只需使用检索到的系列并将其分配给产品。例如

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

希望有帮助。

于 2013-05-21T22:32:16.457 回答