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

3
  • I just answered, then deleted when I found that someone had already done a better job answering here: stackoverflow.com/questions/29825604/… this example is storing an array of Double, but same approach applies for String. Commented Mar 10, 2017 at 20:10
  • Ya that helps a lot. I saw that and was wondering if anything had changed in swift 3. Also this may be a dumb question but now since NSObjects are managed by Xcode, how do I get reference to them so I can change the transformable to [string] Commented Mar 10, 2017 at 20:20
  • Not a dumb question! Undeleted and edited by answer with a note about this. Commented Mar 13, 2017 at 14:23

1 Answer 1

10

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
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I'm getting \n \ in between every different string the array. Does it have to do with converting from Array to NsArray, a core data thing, or something else?
No - the characters in the array shouldn't be transformed, so won't have \n or any other unexpected characters unless you're adding them somewhere!
In what file do you put the extension? I'm kind of confused on that part.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.