0

for example here is the portion of my code that adds values

do {
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "users")
        let results = try context.executeFetchRequest(request)

        if results.count > 0 {
            for item in results as! [NSManagedObject] {
                let fName = item.valueForKey("firstName")
                let lName = item.valueForKey("lastName")
                print(lName!, lName!)
            }
        }

    } catch {
        print("There was error getting data")
    }

Let's say I have 10 users and now I want to

1. Delete users with lastName of "DOW"
2. First 2 users and last 2 users?
3. Also, all users with the lastName starts with "D"

Thanks Borna

2 Answers 2

2

You can code:

if results.count > 0 {
    for item in results as! [NSManagedObject] {
        let fName = item.valueForKey("firstName") as! String
        let lName = item.valueForKey("lastName")
        print(lName!, lName!)
        if fName.contains("DOW"){
            appDelegate.managedObjectContext.deleteObject(item)
        }
    }
}

OR just get object what you want what NSPredicate and delete it code:

let fetchRequest = NSFetchRequest(entityName: "users")
    fetchRequest.predicate = NSPredicate(format: "firstName beginswith[c] %@", "D")
    fetchRequest.returnsObjectsAsFaults = false
    do{
        let fetchResults = try appDelegate.managedObjectContext..executeFetchRequest(fetchRequest)
        if fetchResults.count>0 {
              appDelegate.managedObjectContext.deleteObject(fetchResults[0])
        } else {
            // no data
        }
    }catch{
        //error
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the info. I got confused by this portion of the code appDelegate.managedObjectContext.deleteObject(data) What is (data) and appDelegate?
Sorry, my false. data is item and appDelegate :S , not good if you don't know (youtube.com/watch?v=3IDfgATVqHw)
Thanks so much. Got it working let appDelegate: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
0

This question sounds like homework. The problem with deleting the first 2 and last 2 items is the data is stored unordered. You may get a different set of data from fetch request unless a sort order is provided.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.