开发者

How to delete an unsaved managed object safely?

开发者 https://www.devze.com 2023-04-04 22:11 出处:网络
My app offers some sort of editor functionality for \"text articles\". My editor has two modes. When the editor loads, I create a managed object if it hasn\'t been passed in through the initializer. W

My app offers some sort of editor functionality for "text articles". My editor has two modes. When the editor loads, I create a managed object if it hasn't been passed in through the initializer. When the user cancels a new edit, I delete the object from the context. However, sometimes,I get an error about the object not being inserted into the context, and sometimes I don't. So, is the following code a good approach to check if a managed object instance was inserted into a context?

if ([[self.workingManagedObjectInstance managedObjectContext] isEqual:self.managedObjectContext]){

}

My theory is that if 开发者_如何学编程[self.workingManagedObjectInstance managedObjectContext] is nil, then it hasn't been inserted and will not be "isEqual". Is that a valid way to check that we're not deleting an object that wasn't inserted yet?


If possible should always use the same managed object context, not various instances of it. If you have more than one view controller, you should pass the same context as a reference. Comparing the context does not tell you anything about the existence of an entity instance.

After you initialize the object in the usual way

myEntity = [NSEntityDescription insertNewObjectForEntityForName:@"Entity" 
   inManagedObjectContext:self.managedObjectContext];

you can check if it exists and delete it with a simple

if (myEntity) { 
   [self.managedObjectContext deleteObject:myEntity];
}


In my case, I realized that I should be saving my context after creating the initial instance of the managed object. Since I still had a reference to it, I was able to delete it later.

0

精彩评论

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

关注公众号