使用MagicalRecord使用当前实体创建新实体使用MagicalRecord创建新实体

问题描述:

我想创建一个使用现有实体(传入)设置所有值的新实体。下面是类的方法,我使用的管理对象子类:使用MagicalRecord使用当前实体创建新实体使用MagicalRecord创建新实体

+(FlightManifest *)getNextFlightManifestLegWithFlightManifest:(FlightManifest *)fm { 
    // Get the current context 
    NSManagedObjectContext *moc = [NSManagedObjectContext MR_contextForCurrentThread]; 

    // Set a var to the cur leg so we can use it to increment the leg number later 
    NSInteger curLeg = [fm.leg intValue]; 

    // Check to see if we already have the next leg saved 
    if ([self getFlightManifestWithTripID:fm.tripid andLeg:[NSNumber numberWithInt:curLeg + 1]] !=nil) { 
     return [self getFlightManifestWithTripID:fm.tripid andLeg:[NSNumber numberWithInt:curLeg + 1]]; 
    } else { 
     // Create a new leg using the passed in FlightManifest for the values 
     FlightManifest *newFM = [FlightManifest MR_createInContext:moc]; 

     // Set the value of the newly created object to the one passed in 
     newFM = fm; 

     // Increment the leg number 
     newFM.leg = [NSNumber numberWithInt:curLeg + 1]; 

     // Save the object 
     [moc MR_save]; 

     return newFM; 
    } 
} 

我这样称呼它:

- (IBAction)nextLegButtonPressed:(id)sender { 

    currentFlight = [FlightManifest getNextFlightManifestLegWithFlightManifest:currentFlight]; 
    self.legNumberLabel.text = [currentFlight.leg stringValue]; 
    [self reloadLegsTableViewData]; 
} 

正在发生的事情是,我改变了当前实体,而不是创建一个新的。关于我做错什么的想法?

+0

您需要分享MR_createInContext的代码 – melsam

+1

这是MagicalRecord API的一部分 –

这似乎是显而易见,但此行显得可疑:

// Set the value of the newly created object to the one passed in 
    newFM = fm; 

这将使代码中使用现有的FM对象之后...和改变的人你试图复制...

+0

是的,我试图从传入的所有属性中复制所有属性,然后更改其中一个属性(腿)。由于ManagedObjects没有复制方法,因此除了设置每个属性之外,我不确定还有什么可以做的:newFM.tripid = fm.tripid;这是顺利的,但它肯定不是最有效的方法。 –

+2

这正是你需要做的事情:(如果你从一个托管对象执行深拷贝到另一个托管对象,你将有效地复制整个对象图形。在这种情况下,手动复制属性看起来是最好的方式去, – casademora

+0

好的,如果你把最后的评论放在你的答案中,我会接受它的,谢谢。 –