【问题标题】:Make a relationship with one object already exists与已存在的一个对象建立关系
【发布时间】:2013-05-21 21:50:11
【问题描述】:

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

AllFamilleAllProduit 是两个不同的实体。如何建立它们之间的关系?

家庭创建:

-(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");
    }            
}

【问题讨论】:

    标签: objective-c core-data entity-relationship nsmanagedobject


    【解决方案1】:

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

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

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

    例如,创建从AFAP 的名为toAllProduits 的一对多关系。从APAF 创建一个名为toAllFamille(逆向)的关系。

    查看我的上一个答案:Setting up a parent-child relationship in 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
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      • 2022-06-25
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多