使用核心数据Swift 3保存数组? [英] Saving an array with core data Swift 3?
问题描述
我正在尝试将Core Data中的数组保存为属性。 allImages将被分配给[String]。我见过一些人说它可以变形。将其保存到核心数据中的正确解决方案是什么?
怎么做我得到它们的引用,所以我可以将转换为
[String]
这实际上是一个好点,因为
然后创建一个扩展并添加一个在 NSArray
和Swift <$ c $之间强制转换的计算属性c>数组输入:
扩展名CoreDataArrayObj {
var images:[String] {
得到{
返回imagesArray为?阵列<字符串> ?? []
}
设置{
imagesArray = newValue as NSArray
}
}
}
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?
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
}
}
}
这篇关于使用核心数据Swift 3保存数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!