Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving an array with core data Swift 3?

I'm trying to save an array within Core Data as a property. allImages is going to be assigned to a [String]. I've seen some people say to make it transformable. What is the proper solution to saving this into core data? enter image description here

like image 689
bradford gray Avatar asked Mar 14 '26 22:03

bradford gray


1 Answers

how do I get reference to them so I can change the transformable to [String]

This is actually a good point because the answer I linked too assumed that you were creating your own NSManagedObject subclasses.

It's worth emphasizing that creating/maintaining your own NSManagedObject subclasses by yourself is a perfectly valid option, some might even suggest that it is a preferred option because you get better visibility of any changes overtime if your project is in a repository.

However - last couple of Core Data projects I have been using Xcode to create the subclasses which means you need create another property in an extension.

Here's the general approach that I've been using:

First, in your model file, I name the attribute with the type of object that it represents, in this case an array:

enter image description here

Then create an extension and add a computed property that casts between NSArray and Swift Array type:

extension CoreDataArrayObj {
    var images: [String] {
        get {
            return imagesArray as? Array<String> ?? []
        }
        set {
            imagesArray = newValue as NSArray
        }
    }
}
like image 198
MathewS Avatar answered Mar 17 '26 13:03

MathewS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!