Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: Check if coredata object still exists?

I have a problem with two different view controllers. Each one is in a tab bar of my app. And one view controller influences the other one. In my tab bar item 1 (view controller 1) I edit all my database objects. You can add, delete and edit entities in my database there.

In view controller 2, you can select these entities and add subcategories to these entities and edit them as well. But if you are within a certain entity in view controller 2, switch back to view controller 1, delete that entity and switch back to view controller 2, my app crashes. Of course, because the model of this view controller (the just deleted entity) doesn't exist anymore. So how can I check for that in my viewWillAppear? This doesn't work:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if(!self.myEntity){
        self.isNotExistingAnymore = YES;
        NSLog(@"YES;");
    }
}
like image 292
MichiZH Avatar asked Oct 29 '25 22:10

MichiZH


1 Answers

NSManagedObject has a isDeleted method that returns YES if the object has been marked for deletion in the managed object context.

If the context has been saved so that the object is actually deleted from the persistent store, then its managedObjectContext method returns nil.

So this covers both situations:

if (self.myObject.isDeleted || self.myObject.managedObjectContext == nil) ...
like image 124
Martin R Avatar answered Nov 01 '25 13:11

Martin R