繁体   English   中英

如何在Swift中使用CoreData存储自定义对象?

[英]How to store custom object with CoreData in Swift?

我有一个名为Chord的类,它将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")
}
}

我想使用CoreData持久存储一个名为Song的对象。 Song对象的属性是Chord数组。 所以我将NSManagedObjectNSManagedObject如下:

import Foundation
import CoreData

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

基本上我被困在那里了。 我在CoreData模型视图中将属性的类型设置为BinaryData ,并在将ManagedContext和NSKeyedArchiver.unarchiveObjectWithData(myObject) as? [Chord]保存为之前尝试使用NSKeyedArchiver.archivedDataWithRootObject(myObject) NSKeyedArchiver.unarchiveObjectWithData(myObject) as? [Chord] NSKeyedArchiver.unarchiveObjectWithData(myObject) as? [Chord]获取实体后,但是当我取消归档NSData我得到了一个UILabel对象,虽然我已经设置as? [Chord] as? [Chord]

任何人都可以让我走正确的路?

这里有几个非常重要的事情:

首先, 将UI对象保存到Core Data或任何数据文件是一个糟糕的主意 在技​​术上可以做你想做的事情,但这是非常糟糕的设计。 您应该保存数据,而不是UI对象。 您应该根据数据配置UI,而不是保存实际的UI对象。 虽然MVC是一种策略而不是铸铁规则,但将模型和视图混合到这个程度是一个非常糟糕的主意。 您应该做的是保存模型中和弦的所有相关数据(详细信息如名称等),但不是用于显示它的实际UILabel

其次,纯粹是为了理解核心数据而不是在这种特定情况下应该做的事情 - 如果你想在Core Data中保存自定义对象,你需要确保你的对象的类符合NSCoding 如果对Core Data属性使用“transformable”类型,Core Data将使用NSCoding方法对自定义对象进行编码/解码。 UILabel符合NSCoding ,所以如果这对UILabel来说是一个好主意,它不是 ,你需要覆盖子类中的NSCoding方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM