I’m interested in writing a method which returns an object of class Document, according to some query about the document’s name.
Document happens to subclass NSManagedObject, but the consumer doesn’t really care about that. The Document object is successfully faulted inside the method, and its properties are accessible. However, once the method is left and the NSManagedObjectContext used for the fetch is deallocated, the object once again turns into a fault.
Is there a way to detach the NSManagedObject from its context, so it doesn’t turn into a fault? Of course this would not allow saving changes to the object, but I’m not interested in that anyway.
I would hate to resort to either:
- Writing a
NonManagedDocumentclass which mirrors theDocumentclass. - Tagging along with an
NSManagedObjectContextfor as long as I’m interested in the Documents. The consumer doesn’t care and doesn’t have to be aware of the fact thatDocumentsubclassesNSManagedObject.
Note:
I would add that even if I were able to keep the Document after the NSManagedObjectContext, it wouldn’t be a great solution, since a consumer would have access to the Documents interface as an NSManagedObjectContext subclass, which is undesirable as it may lead to unexpected bugs. But the alternative of manually having to write a freeze-dry wrapper for each model object which happens to be stored in the DB is very unattractive.
You can’t –
NSManagedObjectsalways remain bound to their context in the Core Data stack. Which makes sense.One possible solution would be to write something similar to mogenerator, but which automatically creates non-managed snapshot classes, and methods on the managed classes which create these copies.
Alternatively, there might be some obj-C trick to generate
NSManagedObjectssubclasses which retain their context, and hide the fact that they subclassNSManagedObject, so consumers are only exposed to the snapshotted properties and not to the wholeNSManagedObjectfunctionality.