开发者

Prevent Cora Data Insertions

开发者 https://www.devze.com 2023-02-25 04:06 出处:网络
Is there any way to get notified when an NSManagedObjectContext is about to insert an object, and then prevent 开发者_运维知识库this? Maybe a method like -shouldInsertObject: or something.

Is there any way to get notified when an NSManagedObjectContext is about to insert an object, and then prevent 开发者_运维知识库this? Maybe a method like -shouldInsertObject: or something.

I am creating a lite version of my app and want a certain entity to have a maximum of three objects. Instead of going over my code and adding an if wherever I create a new instance of that entity, I would like to prevent this in one place.

I looked at the NSManagedObjectContextWillSaveNotification and NSManagedObjectContextObjectsDidChangeNotification notifications but they are both not suitable. When these notifications are posted, objects have already been added.


Maybe you could leverage that Core Data does not store the Entity to the Store when you insert, this only happens when you save the context. So in the method where you save the context, you can build a fetchRequest and get the number of entities already in the store:

- (NSUInteger)countForFetchRequest:(NSFetchRequest *)request error:(NSError **)error

If this is three or more, simply get the objects not yet saved using:

- (NSSet *)insertedObjects

which is a set containing the objects inserted but not yet persisted to the store, and delete these. (warn the user, ask them to buy the full version etc.)

0

精彩评论

暂无评论...
验证码 换一张
取 消