Ios: Delete All Core Data Swift

iOS: Delete ALL Core Data Swift

I have got it working using the following method:

@IBAction func btnDelTask_Click(sender: UIButton){

let appDel: foodforteethAppDelegate = UIApplication.sharedApplication().delegate as foodforteethAppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext
let request = NSFetchRequest(entityName: "Food")

myList = context.executeFetchRequest(request, error: nil)

if let tv = tblTasks {

var bas: NSManagedObject!

for bas: AnyObject in myList
{
context.deleteObject(bas as NSManagedObject)
}

myList.removeAll(keepCapacity: false)

tv.reloadData()
context.save(nil)
}
}

However, I am unsure whether this is the best way to go about doing it. I'm also receiving a 'constant 'bas' inferred to have anyobject' error - so if there are any solutions for that then it would be great

EDIT

Fixed by changing to bas: AnyObject

How to delete all data from core data when persistentContainer is not in App delegate method in swift

One of the solutions can be to use NSBatchDeleteRequest for all entities in the persistentContainer. You can add these methods to your CoreDataStack:

func deleteAllEntities() {
let entities = persistentContainer.managedObjectModel.entities
for entity in entities {
delete(entityName: entity.name!)
}
}

func delete(entityName: String) {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try persistentContainer.viewContext.execute(deleteRequest)
} catch let error as NSError {
debugPrint(error)
}
}

The whole code can be found here

Delete/Reset all entries in Core Data?

You can still delete the file programmatically, using the NSFileManager:removeItemAtPath:: method.

NSPersistentStore *store = ...;
NSError *error;
NSURL *storeURL = store.URL;
NSPersistentStoreCoordinator *storeCoordinator = ...;
[storeCoordinator removePersistentStore:store error:&error];
[[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];

Then, just add the persistent store back to ensure it is recreated properly.

The programmatic way for iterating through each entity is both slower and prone to error. The use for doing it that way is if you want to delete some entities and not others. However you still need to make sure you retain referential integrity or you won't be able to persist your changes.

Just removing the store and recreating it is both fast and safe, and can certainly be done programatically at runtime.

Update for iOS5+

With the introduction of external binary storage (allowsExternalBinaryDataStorage or Store in External Record File) in iOS 5 and OS X 10.7, simply deleting files pointed by storeURLs is not enough. You'll leave the external record files behind. Since the naming scheme of these external record files is not public, I don't have a universal solution yet. – an0 May 8 '12 at 23:00

Deleting all data in a Core Data entity in Swift 3

You're thinking of NSBatchDeleteRequest, which was added in iOS 9. Create one like this:

let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Employee")
let request = NSBatchDeleteRequest(fetchRequest: fetch)

You can also add a predicate if you only wanted to delete instances that match the predicate. To run the request:

let result = try managedObjectContext.executeRequest(request)

Note that batch requests don't update any of your current app state. If you have managed objects in memory that would be affected by the delete, you need to stop using them immediately.

Core Data: Quickest way to delete all instances of an entity

iOS 9 and later:

iOS 9 added a new class called NSBatchDeleteRequest that allows you to easily delete objects matching a predicate without having to load them all in to memory. Here's how you'd use it:

Swift 5

let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Car")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

do {
try myPersistentStoreCoordinator.execute(deleteRequest, with: myContext)
} catch let error as NSError {
// TODO: handle the error
}

Objective-C

NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Car"];
NSBatchDeleteRequest *delete = [[NSBatchDeleteRequest alloc] initWithFetchRequest:request];

NSError *deleteError = nil;
[myPersistentStoreCoordinator executeRequest:delete withContext:myContext error:&deleteError];

More information about batch deletions can be found in the "What's New in Core Data" session from WWDC 2015 (starting at ~14:10).

iOS 8 and earlier:

Fetch 'em all and delete 'em all:

NSFetchRequest *allCars = [[NSFetchRequest alloc] init];
[allCars setEntity:[NSEntityDescription entityForName:@"Car" inManagedObjectContext:myContext]];
[allCars setIncludesPropertyValues:NO]; //only fetch the managedObjectID

NSError *error = nil;
NSArray *cars = [myContext executeFetchRequest:allCars error:&error];
[allCars release];
//error handling goes here
for (NSManagedObject *car in cars) {
[myContext deleteObject:car];
}
NSError *saveError = nil;
[myContext save:&saveError];
//more error handling here

Delete all data from an attribute in CoreData

for delete the all data you can use this function

func deleteAllData(entity: String) {

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: entity)
fetchRequest.returnsObjectsAsFaults = false

do
{
let results = try managedContext.executeFetchRequest(fetchRequest)
for managedObject in results
{
let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
managedContext.deleteObject(managedObjectData)
print("Deleted")
}

} catch let error as NSError {
print(error)
}
}

and after that call the function like this

deleteAllData(entity: "your Entity name")

How to remove a core data class completely from an xcode project?

Go to the .xcdatamodeld file, press on the entity you wish to delete, and just press the delete button on the keyboard. This will delete all the classes that were automatically generated by XCode

Core data delete all relationship entity

Using the example you looked at above linked as "this one".

If you use a predicate that filters the Employees by checking the relationship to Department is nil, that'd return just the data items you want. Then I suggest you could delete all of them.



Related Topics



Leave a reply



Submit