Search code examples
ioscore-dataafnetworkingafincrementalstore

Mapping relationships with AFIncrementalStore


I'm in the process of integrating AFIncrementalStore into my project but I'm having a hard time figuring out how to make relationships work.

Let's say I have two models: Document and Page. A document has many pages (one-many). Each model has an inverse relationship to the other.

So I can do:

myDocument.pages

or

myPage.document

I'm trying to fetch all the pages that belong to a document. I have an AFIncrementalStore subclass and an AFHTTPClient subclass that implement the necessary methods.

I can see that the right REST URI is called (eg. /documents/:id/pages). I can also see that the pages get downloaded and stored into the pages table in the sql database.

The problem is the relationship between the two isn't made. When I look at the DB the foreign key column is empty.

Also if I do myDocument.pages it doesn't return anything.

Do I have to manually link these two when new data is fetched? I'm reading through the AFIncrementalStore source but nothing is sticking out.

Thoughts?


Solution

  • Alright, after a few hours or debugging and reading through AFIS line by line I got it to work, but it required some changes to the REST API.

    Initially I had my API return something like the following (example):

    GET /documents/12/pages
    
    Response:
    {
        title: "My Title",
        body: "Some body text ..."
    }
    

    But in order to make it work nicely with AFIS I had to add a reference to the Document in there, like so:

    Response:
    {
        title: "My Title",
        body: "Some body text ...",
        document: 
        {
            id: "12"
        }
    }
    

    As long as in CoreData the relationship is properly setup, AFIS will loop through relationships and automatically find the relationship "document" and look for that key in the returned object. If your server key doesn't match your core data property then you can override one of the AFIncrementalStoreHTTPClient protocol methods to specify the right object.

    This is working fine for now, I'll report back if something goes wrong.

    Hope that helps someone else out.