Reputation: 11710
Is it possible to prevent Core Data to persist an object?
Let's say if I have a NSManagedObject
subclass with a BOOL
property isTemporary
.
So when a save is called on the context I would do a check on the object:
if (self.isTemporary) {
// Do not save
} else {
// Save this object
}
EDIT: More background information for the issue
Hmm to clarify my issue, I create an object, if it exists already I'm the db I fetch it, if it doesn't exist I insert it and set the the temporary flag of the object to YES. I set the flag because it's not clear at this stage if the user will perform a save or cancel action. If he saves I set the flag temporary to NO. If he cancels then I delete the object if temporary flag is YES.
So far so good, but in the meantime in the background there can occur core data save operations in the background that will persist these objects even though I don't want them persisted (because they should be temporary). So if I'm unlucky and app is killed I could have unwanted objects that have the temporary flag set to YES. One option would be to perform a clean operation on startup of the app to remove objects with temporary flag YES. But everything would be a whole lot easier if it would not persist those objects.
Upvotes: 1
Views: 445
Reputation: 12214
If you want to prevent Core Data
from persisting your ManagedObject
, in other words if you don't want your object to be written in the file, you can achieve this by initializing your ManagedObject
in following way:
@implementation MyManagedObject
- (id) init
{
NSEntityDescription* entity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:managedObjectContext];
self = [super initWithEntity:entity insertIntoManagedObjectContext:Nil];
}
@end
Now if you want to save your object, save it in following way:
[managedObjectContext insertObject:myManagedObject];
NSError* error;
if ([managedObjectContext save:&error]) {
NSLog(@"Successfully saveed ManagedObject!");
} else {
NSLog(@"Failed to save ManagedObject!");
}
Hope this helps!
Upvotes: 0
Reputation: 80265
Correct, that is how it can be done.
if (self.isTemporary && self.managedObjectContext) {
[self.managedObjectContext delete:self];
}
Note that the managedObjectContext
of a NSManagedObject
becomes nil once it is deleted.
Upvotes: 1