2

I have a custom class Thing:NSManagedObject with an attribute of adminName.

I am trying to create a copyWithZone function in this Thing class, but when I run the app it says setAdminName doesn't exist.

In my implementation file I am using

@dynamic adminName;


-(id) copyWithZone: (NSZone *) zone
{
Thing *regCopy = [[Thing allocWithZone: zone] init];
regCopy.attendeeNum = [self adminName];

return regCopy;
}

I don't believe I can just change @dynamic to @synthesize since I am using Core Data.

jdog
  • 10,351
  • 29
  • 90
  • 165

2 Answers2

5

NSManagedObject does not conform to the NSCopying protocol. If you want to create a new record with the same data, just insert a new object and assign the values from the first object to the second object.

J2theC
  • 4,412
  • 1
  • 12
  • 14
  • Well, it's not as simple as 'just assign the values from the first object to the second' as the purpose of a copy is to be entirely independent of changes to the other copy. If you copy referenced values from one object to another, then any changes made to that referenced value wind up changing both copies of the NSManagedObject. Yes? – Logicsaurus Rex Jun 25 '17 at 22:56
4

You will need to create a new Thing the same way you created the original Thing something like

Thing *regCopy = [NSEntityDescription insertNewObjectForEntityForName:@"Thing" inManagedObjectContext:self.managedObjectContext]

Nathan Day
  • 5,981
  • 2
  • 24
  • 40
  • Yes, but then you are inserting a new object into the DB, which is not necessarily desirable. – cfischer Apr 22 '15 at 21:46
  • @cfisher If you use NSManagedObject constructor instead of NSEntityDescription, you should be able to set nil as managedObjectContext. That avoids to persist your new object: `[[NSManagedObject alloc] initWithEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:context] insertIntoManagedObjectContext:nil];` – Ben Aug 03 '15 at 15:33