Reputation: 1231
I'm trying to make it so that when the user logs out of my app the CoreData is wiped with the function below.
func wipeMessagesFromDB(){
let moc = managedObjectContext
var array = [cdMessageMO]()
let messageFetch: NSFetchRequest<cdMessageMO> = NSFetchRequest(entityName: "Message")
do {
array = try moc.fetch(messageFetch as! NSFetchRequest<NSFetchRequestResult>) as! [cdMessageMO]//this isnt working!
for managedObject in array
{
let managedObjectData:NSManagedObject = managedObject as NSManagedObject
managedObjectContext.delete(managedObjectData)
}
} catch {
fatalError("Failed to fetch attractions: \(error)")
}
}
The problem is if I call the function when the user logs out, the array length is 0 so nothing is wiped. This is bad because the length shouldn't be 0. I'm 100% there are entries that should be returned because if I call the same function on startup the array is populated.
Any ideas on what's causing this?
Upvotes: 0
Views: 44
Reputation: 2307
Message fetch has the signature NSFetchRequest<cdMessageMO>
let messageFetch: NSFetchRequest<cdMessageMO>
But then you're force casting to NSFetchRequest<NSFetchRequestResult>
array = try moc.fetch(messageFetch as! NSFetchRequest<NSFetchRequestResult>) as! [cdMessageMO]
I'm pretty sure that will always fail (?)
Also, if you're not doing anything with the messages (just want to delete them) you can use the batch delete which is faster because it doesn't actually load the objects into memory:
let context = managedObjectContext
let fetch = NSFetchRequest(entityName: "Message")
let delete = NSBatchDeleteRequest(fetchRequest: fetch)
do {
try myPersistentStoreCoordinator.executeRequest(delete, withContext: context)
} catch {
// handle the error
}
Upvotes: 1