3

The entity is "User" which has 2 attributes(email and password). I want to delete a User with the attribute email = "[email protected]". What do I do? I did this far, but I don't know how to delete with attribute. Which means I need to locate the User first then make the delete.

    let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let context:NSManagedObjectContext = appDel.managedObjectContext!
    context.deleteObject(User: NSManagedObject)
    context.save(nil)

Thank you in advance

1
  • You need to fetch user with desired name and password, then delete it by calling deleteObject method Commented Aug 6, 2015 at 15:13

2 Answers 2

9

You can use a predicate to limit your fetch to only return the object you want, then you can delete it, here's an example:

    let appDel  = UIApplication.sharedApplication().delegate as! AppDelegate
    let context = appDel.managedObjectContext!

    var fetchError : NSError?

    let fetchPredicate = NSPredicate(format: "email == %@", "[email protected]")

    let fetchUsers                      = NSFetchRequest(entityName: "User")
    fetchUsers.predicate                = fetchPredicate
    fetchUsers.returnsObjectsAsFaults   = false


    let fetchedUsers = context.executeFetchRequest(fetchUsers, error: &fetchError) as! [NSManagedObject]

    for fetchedUser in fetchedUsers {

        var deleteUserError: NSError?

        context.deleteObject(fetchedUser)
        context.save(&deleteUserError)
    }
Sign up to request clarification or add additional context in comments.

1 Comment

This works and it's quite clear to understand. Thank you.
2

This should work:

    let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
    let fetchRequest = NSFetchRequest(entityName: "User")
    if let fetchResults = try!managedObjectContext.executeFetchRequest(fetchRequest) as? [User] {
        for (var i=0; i<fetchResults.count; i++) {
            if fetchResults[i].email == "[email protected]" {
                managedObjectContext.deleteObject(fetchResults[i])
                try!managedObjectContext.save()
            }
        }
     }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.