How to save a custom object using CoreData in Swift?

I have a class with a name Chordthat is subclassed UILabel:

import UIKit

class Chord: UILabel {

var numTextLine: Int?
var positionInTextLine: CGFloat?
var tempPosInLine: CGFloat?

init(chordName: String, dLine: DLine, xAxis: CGFloat, posInTextLine: CGFloat) {
    // posInLine: CGFloat
    let labelSize = chordName.sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14.0)])
    let labelPositionY = ((dLine.upLine.frame.height) - labelSize.height) / 2

    super.init(frame: CGRect(origin: CGPoint(x: xAxis, y: labelPositionY), size: labelSize))

    self.numTextLine = dLine.numTextLine
    self.positionInTextLine = posInTextLine

    self.tempPosInLine = self.positionInTextLine

    self.text = chordName
    self.font = self.font.fontWithSize(14)
    self.textAlignment = NSTextAlignment.Center
    self.userInteractionEnabled = true
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    //fatalError("init(coder:) has not been implemented")
}
}

And I would like to save a permanent object with a name Songusing CoreData. An object Songhas an attribute, which is an array Chord. Therefore, I have subclassed NSManagedObjectas follows:

import Foundation
import CoreData

class Song: NSManagedObject {
    @NSManaged var lyrics: NSString?
    @NSManaged var chords: NSData?
    @NSManaged var title: NSString?
    @NSManaged var artist: NSString?
}

And basically, I'm stuck there. I set the attribute type to BinaryDatain the CoreData model view and tried to use it NSKeyedArchiver.archivedDataWithRootObject(myObject)before saving the ManagedContext and NSKeyedArchiver.unarchiveObjectWithData(myObject) as? [Chord]after retrieving the object, but when I unlock NSData, I get the object UILabel, although I set it as? [Chord].

Can anyone get me on the right track?

+4
1

:

-, Core Data . , , . , . , . MVC - , , - . , (, ..), UILabel, .

-, Core Data, -, - Core Data, NSCoding. Core Data "transformable", Core Data NSCoding / . UILabel NSCoding, , UILabel, , NSCoding .

+7

Source: https://habr.com/ru/post/1624192/


All Articles