Search code examples
ioscore-datanspredicateentity-relationshipnsfetchrequest

iOS core data to-one reflexive relationships predicate


I am developing a simple messaging app and use an entity keep relationship between replays. Have setup To-One reflexive relationship as follows.

Reflexive relationship

Now I am struggling to fetch all the reply in to a NSFetchedResultsController to display on a tableview (basically I need to display all previous conversations in a tableview). Could you please help me, how can I do this? Perhaps create a predicate which fetch all the related Memos.

Corrected entity layout. enter image description here


Solution

  • This model doesn't seem right.

    • First, you should name the relationships to describe what they are pointing to.
    • Second, all relationships should have an inverse relationship.
    • Third, don't give your entity a plural name. Call it Memo not Memos. It will make everything easier.
    • Fourth, don't use foreign keys in objects (like staffid) instead create a one-to-many relationship to the staff entity called author or something. With an inverse of authoredMemos or something.

    This messaging app. Is it like SMS texting where only one person can see (and then reply to) each message? Or is it like Twitter where many people can reply to a message?

    SMS Model

    For the SMS type model you should have another entity something like Conversation that has a one to many relationship to the messages it contains. Then you can run a single query to get them all and display them in date order.

    Twitter Model

    For the Twitter type model you should have relationships...

    • replies - [An array of Memo objects]
    • replyTo - [A single memo object]

    These should be inverse relationships.

    Now if a user replies to a memo you can add it in to the replies array of that memo.