0

I am trying to build an app that saves what cars a user owns, and I want to use Core Data to save the car's attributes. I already have implemented the ability to store a single piece of data (like the car's name, manufacturer, year etc). However I want to also store an array of strings. Basically, my object model looks like this:

Name: String
Manufacturer: String
Year: String
Colour: String
features: [String, String, String]

How would I implement this last line which is an array? Previous research tells me to use transformable but I don't know how to

Thanks

I'm using Xcode 13.4 / 14 and SwiftUI

1 Answers1

0

Option 1:
You can create a new entity Feature in your Core Data model with a property description: String, and define a one-to-many relationship from Car to Feature, which will make it a child to Car.
Fetching cars will then give you access to the related features. Look for some Core Data examples on how to implement this.

Option 2:.
You can just add another property features to the Car entity in Core data model, which holds the feautures as ONE string separated by e.g. ,.
Then just divide / concatenate to decode/code:

var features = "one,two,three"

// load
var featureArray: [String] = features.components(separatedBy: ",")

// change
featureArray.append("four")

// save
features = featureArray.joined(separator: ",")
ChrisR
  • 9,523
  • 1
  • 8
  • 26