2017-03-06 108 views
-1

我想根據兩個鍵(分區號&行)對JSON進行排序,並嘗試通過一個錯誤提到的代碼示例。如何對核心數據對象中的字典數組進行排序?

{ 
    "response": { 
     "flightLegId": "FL004", 
     "loadable": [{ 
      "position": { 
       "deckNumber": 1, 
       "compartmentNumber": 1, 
       "leftRight": "ALL", 
       "row": 1 
      }, 
      "uld": { 
       "uldAirline": "KL", 
       "uldNumber": "ULD007", 
       "uldPrefix": "PAG", 
       "commodity": [{ 
        "commodityCode": "C", 
        "airportCode": "GLA", 
        "hasDangerousGoods": false, 
        "pieceCount": 0, 
        "weightKg": 710 
       }] 
      } 
     }, { 
      "position": { 
       "deckNumber": 1, 
       "compartmentNumber": 1, 
       "leftRight": "ALL", 
       "row": 2 
      }, 
      "uld": { 
       "uldAirline": "KL", 
       "uldNumber": "ULD007", 
       "uldPrefix": "PAP", 
       "commodity": [{ 
        "commodityCode": "C", 
        "airportCode": "GLA", 
        "hasDangerousGoods": false, 
        "pieceCount": 5, 
        "weightKg": 780 
       }, { 
        "commodityCode": "M", 
        "airportCode": "GLA", 
        "hasDangerousGoods": false, 
        "pieceCount": 5, 
        "weightKg": 780 
       }] 
      } 
     }] 
    } 
} 

func sortResults(items: [Loadable]) -> [Loadable] { 
      var sortResults: [Loadable] = [] 
      if let sortedArray = (items as NSArray).sortedArray(using: [ 
       NSSortDescriptor(key: "compartmentNumber", ascending: true), 
       NSSortDescriptor(key: "row", ascending: true), 
       ]) as? [Loadable] { 
       sortResults = sortedArray 
      } 
      return sortResults 
     } 
+0

你什麼錯誤?你從哪裏得到它? – Hamish

+0

以下是錯誤信息 ***由於未捕獲異常'NSUnknownKeyException',原因:'[ valueForUndefinedKey:]'終止應用程序:實體Loadable不是密鑰值編碼兼容密鑰「compartmentNumber」。 –

回答

0

使用此功能

func sortResults(items: [Loadable]) -> [Loadable] { 
     var sortResults: [Loadable] = [] 
     if let sortedArray = (items as NSArray).sortedArray(using: [ 
      NSSortDescriptor(key: "position.compartmentNumber", ascending: true), 
      NSSortDescriptor(key: "position.row", ascending: true), 
      ]) as? [Loadable] { 
      sortResults = sortedArray 
     } 
     return sortResults 
    } 
相關問題