Is it possible to return NSManagedObjects as read-only in Core Data?

扶醉桌前 提交于 2021-01-28 01:50:41

问题


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 Boolean readOnlyMode 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 similar readOnlyMode property that you check when save: 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!