Search code examples
ioscore-dataschemaxcode8inventory-management

How to model a "Character-Inventory-Item" schema in Core Data


Essentially I am trying to model a character holding a backpack with items from a pre-determined list. So far I have come up with this.

Core Data Model

My main issue is in understanding how core data handles Arrays/Lists etc. From what I have read that is determined by the relationship, a simple character - item relationship is what I first came up with but I wanted to be able to add custom descriptions per item selected from the pre-determined items (which can be added to by the user at runtime). Each character would have only one "backpack" with a list of items with custom descriptions and custom "amounts" or count. That backpack could theoretically have 2 of the same items but with different descriptions hence having a count of 2 for the one item wouldn't always be appropriate. Also, there is the option for multiple character profiles, so therefore the items could belong to multiple different backpacks, but again with difference in description/count etc.

So I guess my main issue is understanding how Core Data handles lists. And how i could properly address this issue to allow for a "character-backpack-item" relationship.

Thanks!


Solution

  • Short and quick clean-up:

    1: Add the properties from item to your BackPackItem

    2: Remove the itementity

    That backpack could theoretically have 2 of the same items but with different descriptions

    3: Add a property backpackItemID to your BackPackItem and assign a unique ID to it each time you create a BackPackItem entity. That way you can have multiple items with same information but with different ID's. (Not needed , but keeps things more clean in my opinion, do as you wish here)

    Finally:

    Now all you need to do when you fetch is to fetch the Character entity by it's name for example. And in your NSFetchRequest you add the BackPackItem (associatedBackPackItems as the relation is named) as relationshipKeyPathsForPrefetching, and all the associatedBackPackItems will be fetched for you automatically.

    Now let's say you have fetched a Character , and you want to access its BackPackItem --> character.associatedBackpackItems gives you all the items connected to that character.