Saving an array with core data Swift 3?

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-29 05:36:08

问题


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?


回答1:


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
        }
    }
}


来源:https://stackoverflow.com/questions/42726611/saving-an-array-with-core-data-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!