2

I have a very annoying problem with coredata. I have a NSManagedObject sublcass, i.e. "Customer" and everything is fine. Sometime i need to create a new Customer outside the coredata stack, and only in some case i need to save it.

I know i can use NSUndomanager, but it doesn't seem a good idea.

Now i have two classes Customer_managed (subclass of NSManagedObject) and Customer_unmanaged (subclass of NSObject). In Customer_unmanaged i've added a -(void)save method, but this two classes are very coupled, i'm looking for a best pattern.

thanks

IgnazioC
  • 4,554
  • 4
  • 33
  • 46
  • You're not meant to create instances outside of a context, that's specified in the docs. Why do you need to do this? Perhaps there's an alternative approach which avoids needing to do this. – paulbailey Nov 02 '12 at 10:20

2 Answers2

1

You are going about this the wrong way. You should always use a managed object context to create managed objects. If you want to discard it, just delete the object before saving, and it will never touch the persistent store.

If you want to keep the two entities apart, consider using separate contexts.

Alternatively, consider saving the "unmanaged" entities anyway, but marking them with an additional boolean attribute unmanaged. You can then purge them anytime or ignore them when fetching.

Mundi
  • 79,884
  • 17
  • 117
  • 140
  • deleting before save isn't a good idea in my case, maybe my approach is totally wrong, but i need unmanaged object. The second idea is very smart, i can add a boolean and set to true only if i need to add persistency to this object. But i need to change my previous fechrequst, so...i chose the Adun Kjelstrup answer. Thanks everyone. – IgnazioC Nov 03 '12 at 12:53
  • The idea is to be able to pass around the information that is in his managed object in cases where it is only used internally like any other plain ordinary class. Making a copy class with the same members would do the trick but makes redundant code that is hard to maintain. So separate contexts isn't quite right because no context is needed or wanted. it's just a waste of CPU cycles and memory and "disk" space to keep classes used internally in this way. Yeah, I need the same thing and it makes me realize that a MySQL or SQLite database would have been a better choice over Core Data. – David Rector Nov 10 '18 at 01:21
0

It is possible to create a NSManagedObject without a context. Marcus Zarra writes about it in this SO-answer. A word of advice: If you try to create an object with a nil-context, awakeFromInsert: will not be invoked.

Community
  • 1
  • 1
Audun Kjelstrup
  • 1,430
  • 8
  • 13