How can I easily delete all objects in a Realm
Use deleteAll()
:
let realm = try! Realm()
try! realm.write {
realm.deleteAll()
}
Delete All Realm Objects During Runtime
You can do this by using results- For instance, if I want to delete all Dog objects, I can do the following-
// obtain the results of a query
RealmResults<Dog> results = realm.where(Dog.class).findAll();
// All changes to data must happen in a transaction
realm.beginTransaction();
// Delete all matches
results.deleteAll();
realm.commitTransaction();
Ref: documentation
How to delete all records from realm object without fetching it in android?
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
realm.delete(Movies.class);
}
});
In older Realm versions, it was called Realm.clear(Movies.class);
.
Realm Delete an Object in One to Many relationship
The code in the question is very close to being correct, you just need to filter for the product you want to delete instead of the shop. It's not clear if you know the product _id or name but you can filter by either one.
Here's the code to filter for products with an _id of 1 and then delete it (which will also remove it from any lists that contain a reference to it.
const prod = realm.objects('Products').filtered("_id == 1");
realm.write(() => {
realm.delete(prod);
prod == null;
})
The above is taken from the documentation Filter Query and Delete An Object
Keep in mind this will delete all products with id = 1 so as long as _id's are unique it's fine.
Does Realm deleteAll() Reset Primary Keys
Realm.deleteAll()
removes all objects stored in the Realm. The values of primary key properties must be unique amongst objects stored in the Realm. Deleting an object with a given primary key value allows that value to be used for a new object going forwards.
Related Topics
Difference Between Dispatch_Async and Dispatch_Sync on Serial Queue
Prevent Deploying (Disable) Watchkit App with iOS iPhone App in Xcode
What Is the Second Parameter of Nslocalizedstring()
How to Manually Deprecate Members
Swift - Which Types to Use? Nsstring or String
When Should I Use the Various Storage Mechanisms in iOS
Uistackview Distribution Fill Equally
Creating and Playing a Sound in Swift
iOS Blocks and Strong/Weak References to Self
How Does Apple Notify iOS Apps of Refunds of In-App Purchases (Iap)
How to Update a Localized Storyboard's Strings
In iOS, How to Create a Button That Is Always on Top of All Other View Controllers
Getting Device Orientation in Swift
How to Center a Popoverview in Swift
Swift - Check If a Timestamp Is Yesterday, Today, Tomorrow, or X Days Ago
Uiimage Imagenamed Returns Nil
What Is Export * in Module.Modulemap File Inside Each Framework
How to Prevent Uinavigationbar from Covering Top of View in iOS 7