Reputation: 63
I have copied an NSManagedObject
object into a temporary NSManagedObject
object. So that I can use that temporary NSManagedObject
object, if there is no change in the user input. Otherwise, I can use the actual NSManagedObject
object.
The problem is, if I change any value in the actual NSManagedObject
object, it automatically reflects in a temporary NSManagedObject
object. When I searched on the net, they said NSManagedObject
does not conform to NSCopying
protocol. Also, copied object would have a reference to actual NSManagedObject
object.
Is there a way to overcome this problem?
Upvotes: 0
Views: 656
Reputation: 1407
Well, strictly saying, yes, there is. Just create in managed object context new object of that entity-type and copy all you properties into that newly created object one by one.
let objCopy = NSEntityDescription.insertNewObject(forEntityName:<#entityName#>, into:<#context#>)
objCopy.propertyA = objOrigin.propertyA
objCopy.propertyB = objOrigin.propertyB
...
But the very premise of coping managed object inside of the context is a bit obscure to me. NSManagedObject's are only reflect some temporary state of actual piece of data. So, if you need to reverse some changes done to the object, you can always do that. You can ask managed object context, what objects have changed, you can ask managed object about properties that have changed, you have undo()
method, etc.
So, you should consider to review your application design. Pretty sure, you don't need to have temporary copy of you object.
In case, if your copies are not of temporary nature and should be saved into persistent store - you'll have to copy those object manually and property-wise (look the first part of my answer). In case of such coping there will be separate challenge to decide, what to do with references - copy referenced objects (deep copy), or just keep referencing to the same objects as the original
Upvotes: 0
Reputation: 11928
I think it would be helpful to know why you 'need' a temporary NSManagedObject
.
Classes like NSManagedObject
are of reference type. That means both your original and temp object reference the same address in memory and changes to one will be reflected in the other.
However, structs are value type. Maybe you can create a struct that you can initialize with your managed object and use that to store whatever data you need to hold temporarily.
Also, specific to NSManagedObject
s, the idea is that they are temporary. When you change properties on a managed object it's not persisted until you write it to the persistent store with the managed object context.
Upvotes: 1