Reputation: 1794
I have some data that needs to be loaded from the server (backend). For example, let's just say I have an entities of user and event. The relationship between them is many-to-many (user can attend many events and event can have many attendees). All the data is stored remotely on backend and locally in Core Data. When I download data from backend I convert it into NSManagedObjects and store it in NSManagedObjectContext. Everything's very simple, but...
When I download a list of events I want to know, how many attendees this event has. But I cannot download a list of users in the same request, because it's totally overkill. What I need is to download, let's say, a list of users' unique ids so that I can have two things: total number of attendees and means to download detailed data of concrete users (via unique id). Or there's another example: I need to know total number of attendees and download a limited set of them, so I can create some entities in CoreData, but not all of them.
So the main question is how am I supposed to store such information in my CoreData? Meaning I need to know that for some entity there are some related entities in relationship that are not actually currently present in CoreData, but I know how many of them there should be. The first thing that came in my mind is to have a attribute called something like usersCount
in my event entity, but that seems to be kind of dirty. What is the best practice for such situation?
Please comment if the question is not clear enough so I can maybe add some more specifics.
Upvotes: 0
Views: 126
Reputation: 1160
There is nothing dirty about having an attribute to store the count, especially if those entities are retrieved and paged via separate requests.
Upvotes: 1
Reputation: 540145
When you download an event with a list of corresponding user ids, then you can create
the Event
object and also the related User
objects, but you fill only the "userId"
attribute in the user object.
Later, when you download the complete user info, you update the existing (incomplete) objects or create new user objects. Implementing Find-or-Create Efficiently in the "Core Data Programming Guide" describes a pattern that might be useful.
So the idea is to create Core Data objects with incomplete information first and update the objects with detailed information later. The advantage is that you can set up all relationships immediatly, and e.g. counting related users works even if the user information is yet incomplete.
Upvotes: 1