0

I have an Entity on my Core Data called Users. I want to adjust on click on Logout button, delete all data stored in Users entity.

I tried this chunk (that I found from this SO answer)but doesn't work for a reason I couldn't figure out.

func deleteAll() {
        let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
        let context = appDel.managedObjectContext
        let coord = appDel.persistentStoreCoordinator

        let fetchRequest = NSFetchRequest(entityName: "Users")
//Also tried - let fetchRequest = NSFetchRequest(entityName: self.table!)

        let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

        do {
            try coord.executeRequest(deleteRequest, withContext: context)
        } catch let error as NSError {
            debugPrint(error)
        }
    }

Logout Button:

@IBAction func logout(sender: AnyObject) {
      let user = User()
      user.deleteAll()
}

On all(), it is still returning data so deleteAll() doesn't delete anything.

~func all() below is working~

By the way, by using this line, I can access to all data stored in entity.

 let users = User()

 if let allUsers: AnyObject = users.all().result{
        print(allUsers.valueForKey("name"))
        print(allUsers.valueForKey("token"))
 }

and my func all() looks like this:

func all() ->(result: AnyObject?,error: NSError?){
    let request = NSFetchRequest(entityName: self.table!)
    do {
        let fetched = try self.context?.executeFetchRequest(request)
        return (result: fetched, error: nil)
    } catch let error as NSError {
        return (result: nil, error: error)
    }
Community
  • 1
  • 1
senty
  • 12,385
  • 28
  • 130
  • 260

0 Answers0