将自定义对象保存为核心数据属性

时间:2016-01-28 17:45:33

标签: swift core-data

我正在尝试将自定义类保存为核心数据对象的属性。

核心数据对象:

@objc(Safer)
class Safer: NSObject
{
@NSManaged var perakimFiles: [prayer]? //This line gives me an error saying that it cannot save a type that is not Obj. C
@NSManaged var titleEnglish: String?
@NSManaged var titleHebrew: String?
@NSManaged var parshaPerakim: [Int]?
@NSManaged var saferCode: String?
var titles: [[String]]
{
    get
    {
        var ret = [[String]]()
        var i = 0
        for file in perakimFiles!
        {
            ret.append([file.title, "\(i+1)"])
            i++
        }
        return ret
    }
}

init(_ _saferCode: SefarimCodes)
{
    super.init()
    self.saferCode = _saferCode.rawValue
}

init(_perakimFiles: [prayer], _titleEnglish: String, _titleHebrew: String)
{
    super.init()
    self.perakimFiles = _perakimFiles
    self.titleEnglish = _titleEnglish
    self.titleHebrew = _titleHebrew
}
init(_perakimFiles: [prayer], _titleEnglish: String, _titleHebrew: String, _parshaPerakim: [Int])
{
    super.init()
    self.perakimFiles = _perakimFiles
    self.titleEnglish = _titleEnglish
    self.titleHebrew = _titleHebrew
    self.parshaPerakim = _parshaPerakim
    self.saferCode = setTorahSaferCode()!.rawValue
    let config = self.configFromCode()
    self.perakimFiles = config.perakimFiles
}
}

这是我想要在核心数据对象中保存的祷告类:

class prayer
{
var url: NSURL
var title: String
var detail: String?

init(initURL: NSURL, initTitle: String)
{
    print("1")
    print("2")
    self.title = initTitle
    print("3")
    self.url = initURL
    print("4")
}

init(initURL: NSURL, initTitle: String, initDetail: String)
{
    self.url = initURL
    self.title = initTitle
    self.detail = initTitle
}
}

那么我可以对祈祷课做些什么来让它通过核心数据对象保存?我还需要能够在代码的其他地方使用祈祷课的实例。

2 个答案:

答案 0 :(得分:3)

如上所述,让您的祷告类继承NSObject并符合NSCoding,这需要两种方法:-initWithCoder:encodeWithCoder:

实现这些后,您可以使用NSKeyedArchiver/NSKeyedUnarchiver类方法将对象转换为NSData对象并返回,从而允许您将对象存储为受支持的NSData类型下的CoreData属性。

答案 1 :(得分:0)

让类祷告符合NSObject和NSCoding,看看是否能解决错误。