5

I have an Entity called "Item" with an attribute called "colorArray" with type "Transformable".

colorArray could be, for example:

[["Red", "Blue", "Green"], ["Red"], ["Blue", "Green"], ["Green"], ["Blue"], ["Blue", "Green", "Red"]]

I then save colorArray to core data using:

            newEntry.colorArray = colorArray as NSObject

I want to retrieve the colorArray from core data (in the same array format it is saved in), what is the best way to do this?

Florian
  • 5,326
  • 4
  • 26
  • 35
  • It should come out the same as it goes in. What have you tried and what went wrong? – Tom Harrington Jan 30 '18 at 20:05
  • when I try to retrieve the colorArray (array of arrays) using: array2 = entry.colorArray as! [NSArray] I get the message: "Thread 1: Fatal error: NSArray element failed to match the Swift Array Element type" –  Jan 30 '18 at 22:32

1 Answers1

14

I'm not sure why you're using as NSObject or for as! [NSArray], because neither are necessary or useful for the example you give.

With a colorArray attribute configured as follows:

colorArray configuration

It's possible to assign the array from your question to the attribute with

myObject.colorArray = [["Red", "Blue", "Green"], ["Red"], ["Blue", "Green"], ["Green"], ["Blue"], ["Blue", "Green", "Red"]]

Likewise it's possible to retrieve the value with

if let colorArray = myObject.colorArray {
    print("Color array: \(colorArray)")
    colorArray.forEach { (entry) in
        print("Array entry: \(entry)")
    }
}

The value persists in Core Data, so if you kill the app and relaunch it, the data is still there.

You may be overcomplicating this by using those typecasts, and causing errors as a result.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170