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?

- 537
- 2
- 5
- 18
-
I just answered, then deleted when I found that someone had already done a better job answering here: http://stackoverflow.com/questions/29825604/how-to-save-array-to-coredata this example is storing an array of `Double`, but same approach applies for `String`. – MathewS Mar 10 '17 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] – bradford gray Mar 10 '17 at 20:20
-
Not a dumb question! Undeleted and edited by answer with a note about this. – MathewS Mar 13 '17 at 14:23
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:
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
}
}
}
-
1I'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? – bradford gray Mar 14 '17 at 20:41
-
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! – MathewS Mar 14 '17 at 20:48
-
1In what file do you put the extension? I'm kind of confused on that part. – Tyler Cheek Dec 01 '18 at 01:19