Search code examples
core-datansmanagedobjectobjective-c-category

Core Data: Copying NSManagedObject Using Category


I have two entities:

  • Ticket
  • TicketResolved

Both entities have the same attributes. What would be the the most efficient way to copy a Ticket NSManagedObject to TicketResolved NSManagedObject?

I'm thinking using a Category: Ticket+Copy be the least expensive way? If so, I would have to #import both Ticket and TicketResolved in the Category file.

Here is what I came up with, can someone please advise if this is the right way of going about it. I'm using NSManagedObjectSubclass for each entity.

Method in Ticket+Copy:

-(TicketResolved *)copyObjects:(Ticket *)ticket
{
     TicketResolved *ticketResolved = [NSEntityDescription insertNewObjectForEntityForName:@"TicketResolved" inManagedObjectContext:self.managedObjectContext];
     ticketResolved.attribute = ticket.attribute;
     // Assign rest of the ticketResolved attributes values this way
     return ticketResolved;
}

Now calling the Method

#import Ticket;
#import Ticket+Copy;

@implementation
....
Ticket *ticket = [NSEntityDescription insertNewObjectForEntityForName:@"Ticket" inManagedObjectContext:self.managedObjectContext];
TicketResolved *newTicketResolved = [ticket copyObjects:ticket];
// 'newTicketResolved' now has all the keys/values that 'ticket' had.

Is this a right approach or is there a simpler way to do this?


Solution

  • Thanks to @Tom, I did correct my error in the question.

    Below is the solution that worked for me:

    TicketResolved *ticketResolved = [NSEntityDescription insertNewObjectForEntityForName:@"TicketResolved" inManagedObjectContext:self.managedObjectContext];
    NSArray *keys = [[[ticket entity] attributesByName] allKeys];
    NSDictionary *dict= [ticket dictionaryWithValuesForKeys:keys];
    [ticketResolved setValuesForKeysWithDictionary:dict];
    

    The code above does not copy the Relationships Objects. For that I had to use the code below:

    ticketResolved.relationshipObject = ticket.relationshipObject;