如何在iOS上的核心数据中存储Swift Struct? [英] How do I store a Swift Struct in Core Data on iOS?
问题描述
目前我将我的一个类作为NSData存储在plist中,显然这不是一个好方法。
At the moment I'm storing one of my classes as NSData in a plist and obviously that isn't a good way to do it.
所以我'我试图设置核心数据,但我的班级有Structs。这就是我所拥有的:
So I'm trying to set up Core Data, but my class has Structs. This is what I have:
import Foundation
import CoreData
class Favourite: NSManagedObject {
@NSManaged var origin: Stop
struct Stop {
var name: String;
var id: String;
}
}
但这不好,因为它说
属性不能标记为@NSManaged,因为其类型无法在Objective-C中表示
此外,如果没有发生此错误,我不知道我在xcdatamodeld文件中设置了什么。
Furthermore, if this error did not occur, I don't know what I'd set it up as in my xcdatamodeld file.
我想我可以存储值在结构中并分配对象的初始化?这是最优/干净的方式吗?
I guess I could store the values in the struct and assign on initialisation of the object? Is this the most optimal/clean way?
推荐答案
我会这样做:
import Foundation
import CoreData
struct Stop {
var name: String;
var id: String;
}
class Favourite: NSManagedObject {
@NSManaged var name: String
@NSManaged var id: String
var stop : Stop {
get {
return Stop(name: self.name, id: self.id)
}
set {
self.name = newValue.name
self.id = newValue.id
}
}
}
非常有趣的文章,你应该阅读: http:/ /www.jessesquires.com/better-coredata-models-in-swift/
Very interesting article, you should read: http://www.jessesquires.com/better-coredata-models-in-swift/
这篇关于如何在iOS上的核心数据中存储Swift Struct?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!