问询RealmList的remove方法作用:User与Task 1:N关联场景
remove() method do in a 1:N relationship? Great question—this is a frequent point of confusion when working with Realm's relational models! Let's break it down clearly:
When you call remove() on a managed RealmListRealmUser.getTasks()), it only breaks the relationship/link between the RealmUser and the specific RealmTask object—it does not delete the RealmTask itself from the Realm database.
Why is that?
Realm's 1:N relationships are reference-based. A single RealmTask could potentially be linked to other objects (even in your 1:N setup, it might exist independently in the database without any parent references). Realm doesn't assume you want to delete the child object just because you remove it from a parent's list.
Example to clarify the difference
// Get a managed RealmUser and its tasks RealmUser managedUser = realm.where(RealmUser.class) .equalTo("id", targetUserId) .findFirst(); // Grab a task from the user's list RealmTask taskToModify = managedUser.getTasks().get(0); // 1. This only removes the task from the user's RealmList—task still exists in Realm managedUser.getTasks().remove(taskToModify); // 2. This actually deletes the task from the Realm database entirely taskToModify.deleteFromRealm();
If you want to delete child objects when removing them from the list
If your use case requires deleting the RealmTask when it's removed from the user's list, you'll need to do this explicitly in a Realm transaction:
realm.executeTransaction(r -> { RealmTask taskToDelete = managedUser.getTasks().get(0); managedUser.getTasks().remove(taskToDelete); taskToDelete.deleteFromRealm(); });
Alternatively, if you want child objects to be automatically deleted when the parent is deleted (cascade delete), you can use Realm's @CascadeOnDelete annotation (available in Realm Java 5.0 and later) on your RealmList field:
public class RealmUser extends RealmObject { // ... other fields @CascadeOnDelete private RealmList<RealmTask> tasks; // ... getters/setters }
内容的提问来源于stack exchange,提问作者elnino

