Rich
Rich

Reputation: 553

How to synchronise Core Data relationships?

I'm creating an app that pulls data from a web server (MySQL), parses it and stores it in a SQLite database using Core Data.

The MySQL database has a 'words' table. Each word can be in a 'category'. So the words table has a field for 'category_id' to join the tables.

I'm having some trouble getting my head around how to replicate this locally in my app. I currently have entities matching the structure of the MySQL database, but no relationships. It seems like in my 'words' entity I shouldn't need the 'category_id' field (I should instead have a one-to-one 'category' relation set-up).

I'm confused as to how to keep this Core Data relationship in sync with the web server?

Upvotes: 0

Views: 817

Answers (1)

Paul.s
Paul.s

Reputation: 38728

Assuming you have an Entity for Word and Category you will need to make a relationship (naming may be a bit hazy). Also assuming a Category can have many words and

// Word Entity
Relationship    Destination    Inverse
category        Categories     words

// Category Entity
Relationship    Destination   Inverse
words           Word          category       // To-Many relationship

You are correct you would not need the category_id field as all relationships are managed through the object graph that Core Data maintains. You will still need a primary key like server_id (or similar) in each entity or you will have trouble updating/finding already saved objects.

This is how I deal with syncing data from an external database (I use RESTful interfaces with JSON but that does not really matter)

  1. Grab the feed sorted by server_id
  2. Get the primary keys (server_id) of all the objects in the feed
  3. Perform a fetch using the a predicate like ... @"(serverId IN %@)", primaryKeys which is sorted by the primary key.
  4. Step through each array. If the fetch result has my record then I update it. If it does not then I insert a new one.
  5. You would need to do this for both Word and Category
  6. Next fetch all objects that form part of a relationship
  7. Use the appropriate methods generated by core data for adding objects. e.g. something like `[myArticle addWords:[NSSet setWithObjects:word1, word2, word3, nil];

It's hard for me to test but this should give you a starting point? Good to see a fellow Shiny course attendee using stack overflow - it's not just me

Upvotes: 1

Related Questions