Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving custom object as core data property

I am trying to save a custom class as a property of a core data object.

The Core Data object:

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

Here is the prayer class that I am trying to save in the core data object:

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

So what can I do to the prayer class to make it savable by the core data object? I need to also be able to use instances of the prayer class in other places of the code.

like image 894
DaniSmithProductions Avatar asked Dec 06 '25 05:12

DaniSmithProductions


1 Answers

As mentioned, have your prayer class subclass NSObject and conform to NSCoding which requires two methods : -initWithCoder: and encodeWithCoder:

Once those are implemented, you can use NSKeyedArchiver/NSKeyedUnarchiver class methods to transform your objects into NSData objects and back, thus allowing you to store your objects as CoreData properties under the supported NSData type.

like image 110
JERSH Avatar answered Dec 07 '25 19:12

JERSH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!