问题
I'm using Core Data for caching of server data in a module that I'm writing and would like to be able to enforce that other parts of the application don't modify that data.
Is is possible to mark either my instances of NSManagedObject, or the NSManagedObjectContext used to fetch them, as read-only? Since the context is accessible directly from the object, consumers are free to modify the object and call [obj.managedObjectContext save:&errror]
.
I've seen plenty of references to creating a completely read-only store (like here: Unable to create a readonly sqlite store in Core Data: Cocoa Error 260), but I don't want the NSPersistentStore itself to be read-only (the module I'm writing should be able to write to it).
One option is to convert the managed objects into plain NSObject subclasses with the same properties. But then I lose some of the nice things like lazy loading, etc, that Core Data can do.
Any ideas?
回答1:
NSManagedObject
doesn't support a read-only state on its own, so it's not a trivial matter. There are some slightly-hackish things you can do to get something like you describe, though.
- If you're using custom subclasses of
NSManagedObject
, you could add a BooleanreadOnlyMode
property to the class (not to the entity). Then you could override the setter methods to check this property before doing anything. You'd get per-object read-only behavior, but there's nothing to stop other parts of the app from just changing that value. - You could do something similar on the
NSManagedObjectContext
itself. Create your own subclass, which you always use, and add a similarreadOnlyMode
property that you check whensave:
is called. But anyone could change that flag.
Or you could do it the harsh way. Use a Boolean readOnly
variable in one of your own controller classes. Then listen for NSManagedObjectContextObjectsDidChangeNotification
. If that notification arrives during read-only mode, crash the app. If the rest of the app is being developed by people ostensibly on the same team as you, this should be entirely reasonable since it'll only happen in-house during app development.
来源:https://stackoverflow.com/questions/33292161/is-it-possible-to-return-nsmanagedobjects-as-read-only-in-core-data