Deleting Relationship Objects with Cascade in Core Data

荒凉一梦 提交于 2021-01-27 05:16:48

问题


I'm looking to perform some simple deletion with Core data but just need a bit of advice on this one please.

I have a model with Transaction, Name, Event and Date Entities. The Transaction has a link to each of the other Entities.

In the app, when a user adds in information to text fields, that gets saved to a 4 tab table view controller.

The first tab is using NSFetchedResultController with a fetchRequest on the Transaction Entity. The second tab is using the Name Entity, the third is using the Event and the fourth is using the Date Entity.

If I delete an entry from the Transaction tab, it deletes just that transaction which makes sense.

What I want is to be able to delete a person from the Name tab, or an event from the Event tab and have that cascading through the model of the app. So if Bob has multiple transactions, deleting him the transaction tab will delete that one transaction.

If I delete BOB from the name tab, it should deleting him from every event that he was part off with every date and Transaction.

The same applies for the events and dates.

EDIT: Update to include data model

Note: Year Entity is experimental and currently not being used enter image description here How would I go about doing something like this?

Thanks


回答1:


If you set the "Deletion Rule" for the "transactions" relationship from Person to Transaction to "Cascade", then deleting a person will automatically delete all related transactions.




回答2:


First, I cannot see the wisdom of abstracting dates into entities. Maybe you can enlighten me. In my mind, the date belongs to the transaction. On the date tab you still have to fetch transactions but present them grouped and sorted differently.

I suppose you know how to make your Person-to-Transactions relationships cascade. This will remove all transactions associated with a person. The same applies to Event.

Cascading in the other direction, however is more problematic. You have to somehow check if it is the last member of the to-many relationship and only delete it if it is. One way to do that is to override the setters. In your generated NSManagedObject subclasses you will find the auto generated setters, including those for adding or removing objects from sets (i.e., to-many relationships).

-(void)removeTransactionsObject:(Transaction *)value {
    [super removeTransactionsObject:value];
    if (!self.transactions.count) {
       [self.managedObjectContext deleteObject:self];
    }
}


来源:https://stackoverflow.com/questions/20528011/deleting-relationship-objects-with-cascade-in-core-data

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