2017-03-02 32 views
1

我保存的對象中的核心數據,我期待如何將這些對象作爲一個字典如何在Swift中將核心數據對象讀入Dictionary?

這裏取的是我的代碼示例,其中部分是用於字典和公司作爲核心數據對象的數組鍵。

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

fatal error: unexpectedly found nil while unwrapping an Optional value

誰能幫我這個問題?

+1

根據提取請求,提取的對象始終以**數組**的形式返回,可以是[NSManagedObject]或[[String:Any]]。 – vadian

回答

1

該錯誤消息意味着您強制展開沒有值的可選項。換句話說,你正在使用!,你不應該。 (你應該基本上從來不使用武力展開操作(!)。)

讓我們看一下行,你這樣做:

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

哪裏status是返回String像「待定」或「主動」上Company的發明特性。

+0

我試過使用你的代碼,現在我有另一個問題。所以,我只能爲每個部分節省1個公司(「活躍」和「待定」)。該部分可以有多個公司嗎?我創建一個字典的主要目的是用table來填充tableView。 @戴夫 –

0

我找到了解決方案,只需要使用NSFetchResultController以在不同部分顯示TableView中的數據。