使用swift从Core Data中获取会导致崩溃,因为我收到了其他类型的对象

时间:2015-11-19 14:32:08

标签: ios swift core-data

我使用Swift从Core Data中获取对象,而不是使用"主题"对象我得到NSManagedOBject

Class Enity:

enter image description here

分类:Themes.swift

import Foundation
import CoreData

    @objc(Themes)
    class Themes: NSManagedObject {

    }

类:主题+ CoreDataProperties.swift

import Foundation
import CoreData

extension Themes {

    @NSManaged var themeName: String?
    @NSManaged var topBarColors: NSData?
    @NSManaged var bottomBarColors: NSData?
    @NSManaged var bottomBarIconsColor_default: NSData?
    @NSManaged var bottomBarIconsColor_selected: NSData?
    @NSManaged var background_image: NSData?
    @NSManaged var isBackgroundBlured: NSNumber?
    @NSManaged var font_phoneTitle: NSData?
    @NSManaged var font_name: NSData?
    @NSManaged var font_phoneNumber: NSData?
    @NSManaged var font_barButtons: NSData?
    @NSManaged var font_organization: NSData?
    @NSManaged var font_initiala: NSData?
    @NSManaged var isPredefined: NSNumber?
    @NSManaged var isRandomInitialBackgroundColor: NSNumber?
    ///0 gratis, 1 cu bani etc
    @NSManaged var priceTier: NSNumber?

}

撷取:

func fetchThemes() {
    let moc = AppDelegate().managedObjectContext
    let personFetch = NSFetchRequest(entityName: "Themes")

    do {
        let fetchedPerson = try moc.executeFetchRequest(personFetch) as! [Themes]
        print("fetched: \(fetchedPerson)")
        arr_themes = fetchedPerson

    } catch {
        fatalError("Failed to fetch person: \(error)")
    }
}

我得到了这个并且崩溃了:

enter image description here

知道问题可能是什么?

1 个答案:

答案 0 :(得分:2)

主题是NSManagedObject的子类。不清楚你为什么以这种方式使用制定者和吸气剂,你根本不需要这样做。在任何情况下,NSManagedObject都不会被指定为颜色。您可能希望查看以下SO Answer。您还可以在该答案的右侧搜索相关问题,以便您可以很好地了解如何存储,检索核心数据上的UIColor。谷歌将生成使用UIColor和核心数据的详细代码。

这个要点是:

  1. 创建一个属性以存储颜色并标记为Transformable
  2. 为Themes对象生成NSManagedObject子类
  3. 从NSObject更改生成的类型?到UIColor?
  4. 将导入UIKit添加到主题子类文件
  5. 的顶部

    正确创建类后,您可以在代码中执行以下操作(Core Data将自动管理UIColor存储)。

    //Themes class after regeneration when you set the attribute to Transformable in the Core Data Model Editor and regenerate
    @NSManaged var backgroundColor: NSObject?
    
    //after you update to support adding a UIColor
    import UIKit
    //...
    @NSManaged var backgroundColor: UIColor?
    
    //create your new Themes object
    var colorObject:Themes = //...
    
    //Set the backgroundColor attribute 
    colorObject.backgroundColor = UIColor().redColor()