如何在Swift中将核心数据对象提取到Dictionary中?

时间:2017-03-02 04:03:02

标签: swift xcode dictionary core-data

我已经在核心数据中保存了对象,我正在寻找如何将这些对象作为字典获取

以下是我的代码示例,其中sections是字典的键,Company是核心数据对象的数组。

private var companies = Dictionary<String, Array<Company>>()
private var sections: [String] = ["Pending", "Active", "Pending"]

override func viewWillAppear(_ animated: Bool) {
    let fetchRequest : NSFetchRequest<Company> = Company.fetchRequest()
            let moc = DatabaseController.getContext()
            do {
                let request = try moc.fetch(fetchRequest)
                for case let (index, object) in request.enumerated() {
                   companies[sections[index]]!.append(object)
                }
            } catch let error as NSError {
            print("Could not fetch. \(error), \(error.userInfo)")
        }}

当我尝试执行代码时,出现错误:

enter image description here

  

致命错误:在解包可选值时意外发现nil

有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

该错误消息表示您强制解包没有值的可选项。换句话说,你使用的是!。 (你基本上不应该使用force unwrap运算符(!)。)

让我们来看看你这样做的路线:

companies[sections[index]]!.append(object)

如果我们将其分解并添加我们推断的类型:

let section: String? = sections[index]
let companyArray: Array<Company> = companies[section]!

你崩溃是因为companies开始为空,所以要求任何数组都会返回nil。 (实际上,我不确定你的代码是如何编译的,因为你不能用可选的下标到字典中。)

但是,如果您解决了这个问题,我们仍然会遇到问题,因为您正在使用获取数组的索引来查找该部分。如果您有三家以上的公司,那将开始失败。

我怀疑你想要这样的东西:

for let company in result {
    if var companyArray = companies[company.status] {
        companyArray.append(company)
    } else {
        companies[company.status] = [company]
    }
}

statusCompany上发明的属性,返回String,如“待定”或“有效”。

答案 1 :(得分:0)

我找到了解决方案,只需要使用NSFetchResultController,以便在不同的部分中显示TableView中的数据。