Create new entity with current entity using MagicalRecord
-
13-06-2021 - |
Question
I am trying to create a new entity using an existing entity (passed in) set set all the values . Here is the class method that I am using in the Managed Object Subclass:
+(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;
}
}
And I call it like this:
- (IBAction)nextLegButtonPressed:(id)sender {
currentFlight = [FlightManifest getNextFlightManifestLegWithFlightManifest:currentFlight];
self.legNumberLabel.text = [currentFlight.leg stringValue];
[self reloadLegsTableViewData];
}
What is happening is that I am changing the current entity instead of creating a new one. Any ideas on what I am doing wrong?
Solution
This may seem obvious, but this line seems suspicious:
// Set the value of the newly created object to the one passed in
newFM = fm;
This would make the code after use the existing fm object...and change the one your trying to copy...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow