I am writing an app where I have a dashboard which shows the list of users.So I have created an entity by the name 'User'. For mapping, I am using Alamofire object mapper.
SCENARIO
Before making a call to the API, I am checking if network is available. If no, I fetch the entity from core data and show the saved results. If yes, I make a call to the ApI and get the objects from the API and save it to my context.
PROBLEM
Now when I get the objects from the API, I save the response in NSManagedObjectContext and it gets appended to the already present NSManagedObjects in my 'User' entity.What I want is that if the User is already present in the entity , I don't want to save that User object in my entity again.So in the first call, I have ,say, 20 objects in the DB, after the second call, the count increases to 40 and so on.I don't want that.How do I achieve this?
I used 'unique constraints' to resolve this issue. Its basically like primary key only. So when you add the 'id' in your entity as a unique constraint, the duplicate managed objects won't be stored in the context. Here is the link that you can follow:
http://www.oodlestechnologies.com/blogs/How-to-Implement-Unique-Constraints-in-Core-Data