簡體   English   中英

將對象數組轉換為數組對象

[英]Converting Array of Objects into Object of arrays

我有一個帶有一些不同類型的數組的類,可以說它們都充滿了相同的數量。

public class CoreLocationMap {

var type: [String] = []
var location: [Int] = []
var groupName: [NSString] = []
var x: [Float] = []

init() {}

}

我想要類似JSON對象的內容:

var jsonObject = ({type = myString; location = 123; groupName = anotherString; x = 0.123}, {type = myString; location = 123; groupName = anotherString; x = 0.123}, ...)

不一定要有jsonObject,但我想將變量封裝在邏輯組中,因此

type
location
groupName
x

應該制作一個struct / object / whateever ^^。 例如,如果以后使用某個位置,則要引用該組中的其他變量。 我也對其他解決方案感到滿意。 如果您需要更多詳細信息,請告訴我。

謝謝!

如您所建議的,您可以使用結構來封裝數據:

struct LocationData {
   var type: String
   var location: Int
   var groupName: String
   var x: Float
}

並在您的類中聲明一個數組:

var locationsData = Array<LocationData>()

添加一個用於添加元素的函數:

func addLocationData(type: String, location: Int, groupName: String, x:Float) {
   // Add additional safety/limitation checks
   locationsData.append(LocationData(type: type, location: location, groupName: groupName, x: x) // structs have an implicit init method
}

您可以創建模型,讓我們說locationModel喜歡

  calss locationModel{
     var type:String
     var location : Int
     var groupName : String
     var x: Float

  // you can create Init method to init() model properties 
  // you can create custom method to fill values of model calss

  /* you create custom method that accept array as argument create 
    this class (locationModel) type of object in function load data
    from array to modelobject add modelobject in array and return
    this array.*/
 }

現在,您可以在要使用的地方創建此模型類對象,並用模型類方法填充它們。

例如,如果您想在CoreLocationMap中使用它,請創建位置模型並在您的類中填充它並填充值。

並在新創建的數組中添加此模型對象(如果要對象數組)。 希望對您有幫助。

這個庫為您做同樣的事情JSONModel https://github.com/icanzilb/JSONModel

該庫具有以下方法

    NSArray* jsonObjects = [YourModelClass arrayOfDictionariesFromModels: modelObjects];

此方法從對象數組返回字典數組。

現在,您可以使用

NSJSONSerialization

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM