2015-02-24 191 views
2

我有一個包含一些不同類型數組的類,我們假設它們都填充了相同的數量。將對象數組轉換爲數組對象

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 ^^。 如果我稍後使用某個位置,我想引用該組中的其他變量。 我對其他解決方案也很滿意。如果你需要更多的細節,請告訴我。

謝謝!

回答

2

如你所說,你可以使用結構來封裝數據:

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 
} 
+0

好吧,以及如何填補我CoreLocationMap的結構? – 2015-02-24 09:31:49

+0

你能給我一個你想要的用法的例子嗎? (即使在僞代碼中) – giorashc 2015-02-24 09:32:24

+0

我的數組對於每個類型,位置,groupName和x都有760個值。所以你提到的解決方案應該在locationsData中有760個「組」。 – 2015-02-24 09:36:07

2

您可以創建模型calss讓我們說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中使用這個創建位置模型,並在你的類和填充值中初始化它。

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

0

該庫做同樣的事情,你JSONModel https://github.com/icanzilb/JSONModel

該庫具有以下方法

NSArray* jsonObjects = [YourModelClass arrayOfDictionariesFromModels: modelObjects]; 

該方法返回字典中從對象的數組的數組。

現在,你可以使用

NSJSONSerialization