Search code examples
swiftxcodecore-data

How to store array of custom structs in Coredata


I'm trying to figure out how to store an array of a struct I defined in Coredata in swift. From what I've researched, I think I need to use a transformable attribute, but I haven't found a solid guide on how to do that, and I'm pretty new to swift so I haven't been able to figure it out.

I'm not actually sure if storing an array in Coredata is exactly what I want to do for my purpose so I'll explain my goal. Im creating an app to time Rubik's cube solves. The app allows user to create "instances" with a name and list of times, so that they can use the app for multiple puzzles and keep the times separated. So I have an Instance struct with the name, puzzle, etc.., and a Solve struct that stores a time, and other information about a specific solve. The Instance struct contains an array of Solves.

I'm trying to move this into Coredata, so I now have an Instance entity with the attributes that the Instance Struct had, and I want to store an array of Solves in it. So I'm wondering how I would do this or if there's a better approach I should take.

Thanks!


Solution

  • Sounds like you should create a Solve entity in your CoreData model, then create a To Many Relationship on your Instance entity (e.g. named 'solves') linking to your Solve entity. This will mean each Instance has a Set of associated Solve entities.

    There's more info about creating CoreData relationships here: https://developer.apple.com/documentation/coredata/modeling_data/configuring_relationships