0

I'm requesting data from Rest API and then save them to database with core data.

First API Result

  1. A
  2. B
  3. C

Second API Result

  1. A
  2. C

We should remove 'B' because disappeared from API result. Currently we delete all data in table before add new data, But that does not look right.

My question is how to detect removed data and delete them on database with the least CPU overhead?

I have option to choose Core Data storetype (memory and sqlite) and can't use NSBashRequest

1
  • Before the refresh you could load all off the current identifiers into a set, then remove the identifiers that you get from the server and finally delete the objects remaining in the set. Or, you could add a time stamp and when you fetch updates, set the time stamp on the fetched object before deleting any objects with an earlier time stamp. Commented Dec 24, 2018 at 20:30

1 Answer 1

1

When I had to do this, I did it by fetching everything that was not in the new incoming data set, and deleting everything in the fetch result. This only works if you have a unique ID of some kind-- if your A, B, and C are unique IDs that don't have duplicates.

The code would be something like

  1. First get all unique IDs found in the new incoming data. If the incoming objects are in an array called restResults, this would be something like

    NSArray *incomingUniqueIDs = [restResults valueForKey:@"uniqueID"];
    
  2. Do a fetch request with a predicate that finds everything with a unique ID that not in the new list. Something like

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"uniqueID not in %@", incomingUniqueIDs];
    

Then perform the fetch and delete everything it finds. In your case, on the second time around, incomingUniqueIDs would contain A and C. The predicate would fetch only B. You'd delete that entry, and you'd be done.

Sign up to request clarification or add additional context in comments.

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.