Raffaiele90
Raffaiele90

Reputation: 3

Delete entity data from CoreData

as in the title, I want to delete data from the CoreData when the user logs out from his account

What I wrote is this:

let moc = DataController().managedObjectContext
var context : NSManagedObjectContext?
var entityCurrentValue : NSEntityDescription?
var entityPreviousValue : NSEntityDescription?
var entityLastAccess : NSEntityDescription?

override func viewDidLoad() {

    super.viewDidLoad()


    loadCoreData()


    }
}

func loadCoreData(){
    context = moc

    entityCurrentValue = NSEntityDescription.entityForName("CurrentValue", inManagedObjectContext: context!)
    entityPreviousValue = NSEntityDescription.entityForName("PreviousValue", inManagedObjectContext: context!)
    entityLastAccess = NSEntityDescription.entityForName("LastAccess", inManagedObjectContext: context!)
}

@IBAction func logoutButton_clicked(Sender: UIButton!) {

    PFUser.logOut()

    deleteElement(entityCurrentValue!)
    deleteElement(entityPreviousValue!)
    deleteElement(entityLastAccess!)
    self.performSegueWithIdentifier("loginSegue", sender: Sender)

}

in this function i try to delete elements from the entity

func deleteElement(entity : NSEntityDescription){

    let fetchRequest = NSFetchRequest()
    fetchRequest.entity = entity
    fetchRequest.fetchBatchSize = 50
    var fetchResult = Array<AnyObject>()

    do{
        try fetchResult = (context?.executeFetchRequest(fetchRequest))!
    }catch{
        fatalError()
    }

    for entity in fetchResult as! [NSManagedObject] {
        self.context?.deleteObject(entity)
    }
}

The problem is that when i log out, and than I log in with another account, the app loads data that are already stored into the memory. Can someone help me? Thanks

Upvotes: 0

Views: 312

Answers (1)

deadbeef
deadbeef

Reputation: 5563

A managed object context is only a virtual representation of the data on disk. So when you delete an object from a managed object context, it is not deleted from disk but simply marked as deleted inside the context.

In order to persist the changes of you context on disk, you need to save the context after performing the delete operations, which is what is missing from your code.

Upvotes: 0

Related Questions